0

In spring data jpa Application I created one model with @entity annotation. I am saving that model data into table. I am auto incrementing primary key. But when I am saving data into table it's not sequentially auto incrementing.

@GeneratedValue(strategy = GenerationType.AUTO)

Class file:

@Entity
@Table(name="exception")
public class Exception implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "exception_seq_generator")
    @SequenceGenerator(name = "exception_seq_generator", sequenceName = "exception_seq")
    @Column(name="exception_id")
    public Integer exceptionId;
    
    @Column(name="status_code")
    public Integer statusCode;
    
    public String message;
    public String status;
    public String error;
    //Getter and setter

Table:

enter image description here

Can anyone tell me why the primary key is not auto incrementing sequentially? Why it's not taking 2,3,4.....

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SpringUser
  • 1,351
  • 4
  • 29
  • 59
  • Can you show us the definition of the sequence `exception_seq`? This one is defined in the database. – Ortomala Lokni Mar 27 '18 at 16:01
  • Use the IDENTITY strategy `@GeneratedValue(strategy = GenerationType.IDENTITY)` and if you are auto generating your schema `@Column(name="exception_id", columnDefinition="serial")` – Joe Chiavaroli Mar 27 '18 at 16:03
  • Possible duplicate of [postgresql generate sequence with no gap](https://stackoverflow.com/questions/19004453/postgresql-generate-sequence-with-no-gap) – Jens Schauder Mar 28 '18 at 04:53

1 Answers1

2

First of all try setting the allocationSize:

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "exception_seq_generator")
@SequenceGenerator(name = "exception_seq_generator", sequenceName = "exception_seq", allocationSize=1)
@Column(name="exception_id")
public Integer exceptionId;

Also check your current Sequence in the Database, it might have a wrong value now.

Simpler aproach:

Define the primary-key column in PostgreSQL DB as SERIAL:

CREATE TABLE xy (
   id SERIAL PRIMARY KEY;
);

And annotate the Column with:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

The SERIAL type, creates an auto-increment sequence for you and you don't have that much overhead in you JPA Entities.