membersound
membersound

Reputation: 86627

Hibernate sequence gets multiplied by 50 for `@Id` generation?

private static final String SEQUENCE = "my_seq";    

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
@SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE)
private Long titId;

This creates the following schema:

CREATE SEQUENCE my_seq
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1000
  CACHE 1;

Observation: When I set current value of the sequence to 1, then the first @Id autogenerated is 50. When I set the value to 1000, the first id is 50000.

So, somehow the current valuze of the sequence always gets multiplied by 50. Why? How can I prevent this and just use the nexval from the sequence?

Upvotes: 3

Views: 5165

Answers (2)

Mohamed Afzal
Mohamed Afzal

Reputation: 109

I too faced this issue in Hibernate 5:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
@SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE)
private Long titId;

Got a warning like this below:

Found use of deprecated [org.hibernate.id.SequenceHiLoGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead. See Hibernate Domain Model Mapping Guide for details.

Then changed my code to SequenceStyleGenerator:

@Id
@GenericGenerator(name="cmrSeq", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
            parameters = {
                    @Parameter(name = "sequence_name", value = "SEQUENCE")}
    )
@GeneratedValue(generator = "sequence_name")
private Long titId;

This solved my two issues:

1) The deprecated warning is fixed 2) Now the id is generated as per the oracle sequence.

Upvotes: 1

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31215

This behavior comes from @SequenceGenerator which has a default value of 50 for its parameter allocationSize. You can change it if you want :

@SequenceGenerator(name = SEQUENCE, sequenceName = SEQUENCE, allocationSize = 42)
private Long titId;

This is intended for performance reasons. It allows Hibernate to book a block of ids and prevents from asking the database each time you need a new id.

Upvotes: 5

Related Questions