0

In my current project we are using PostgreSQL as DB and Spring data JPA for persistence. In all entity classes we are using GenerationType.SEQUENCE for generation of primary key value. It's working fine. But, the value for the primary key in each table not starting from 1 . The value is always next increment value of the maximum number of other table's primary key.

How can we change this ? . How to make primary key value of each table should start from 1.

Madhu Sudhan Reddy
  • 607
  • 5
  • 15
  • 22
  • Possible duplicate of [Can I configure Hibernate to create separate sequence for each table by default?](https://stackoverflow.com/questions/6633384/can-i-configure-hibernate-to-create-separate-sequence-for-each-table-by-default) – Jens Schauder Jun 04 '19 at 11:57

2 Answers2

0

You need to configure a sequence per table. This answer explains how to do that.

I'm just quoting it here:

Contents of my package-info.java:

@GenericGenerator(
    name = "optimized-sequence",
    strategy = "enhanced-sequence",
    parameters = {
        @Parameter(name="prefer_sequence_per_entity", value="true"),
        @Parameter(name="optimizer", value="hilo"),
        @Parameter(name="increment_size", value="50")})
package org.example.model;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

On the usage side you just need

@Id @GeneratedValue(generator="optimized-sequence")
public long id;
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
0

Below code on ID worked for me.

@Id
@SequenceGenerator(name = "MY_ENTITY_SEQ", sequenceName = "MY_ENTITY_SEQ", allocationSize=1)
@GeneratedValue(strategy = GenerationType.AUTO, generator = "MY_ENTITY_SEQ" )
@Column(updatable = false, nullable = false)
private Integer id;

Please let me know if i face any issues with this approach in future.

Madhu Sudhan Reddy
  • 607
  • 5
  • 15
  • 22