Hibernate generating two different sequence identifiers for PostgreSQL insertion

I have an entity defined using the primary key generated by the sequence:

@Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_key_gen") @SequenceGenerator(name = "id_key_gen", sequenceName = "id_key_seq") @Column(name = "id", unique = true, nullable = false) public int getId() { return this.id; } 

I use PostgreSQL, and this key is defined as serial. According to PostgreSQL

 select last_value from id_key_seq; 

returns

 1603. 

When I do create () to save an instance of this object, I see the following in my logs (non-related material):


05 15: 15: 26.948 org.hibernate.id.enhanced.SequenceStructure [DEBUG] - The obtained sequence value: 1604

05 15: 15: 26.948 org.hibernate.event.def.AbstractSaveEventListener [DEBUG] - generated identifier: 1554 using the strategy: org.hibernate.id.enhanced.SequenceStyleGenerator


Subsequent SQL insert statements refer to a value of 1554, not what it should use, 1604 (based on the value returned from SequenceStructure. Where did Hibernate get 1554 from?

Hibernate seems to have an error here - SequenceStructure knows the correct next value, but it is not used. Any idea how to solve this?

FYI: I know this page that says use GenerationType.AUTO because "the Hibernate people totally messed it up," but there isnโ€™t much higher than this not-so-useful statement.

+4
source share
1 answer

It looks like if you are using GenerationType.SEQUENCE, you need to specify an โ€œincrement valueโ€ of 1 to avoid using the sequence as a Hi / Lo sample.

The first answer (useful) to the question you posted explains that you need to specify "allocSize = 1" in the @GeneratedValue annotation.

In newer versions of Hibernate, you can set your Hibernate properties instead of hibernate.id.new_generator_mappings=true ; see documents .

+5
source

Source: https://habr.com/ru/post/1334428/


All Articles