Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate 5 sequencegenerator not giving the right value

After migrating to Hibernate 5.2.7, I seem to be getting incorrect values for the id field.

My code:

@Id @SearchableId
@GeneratedValue(strategy=GenerationType.AUTO, generator="hms_seq_gen")
@SequenceGenerator(name="hms_seq_gen", sequenceName="patregn_seq")
protected Integer ID;

Hibernate fires this query:

select nextval ('patregn_seq')
which gives 5367. The last value in the id field in the table is 5358.

And I get this
ERROR: duplicate key value violates unique constraint "patientregistration_pkey" [java] Detail: Key (id)=(5318) already exists.

I am sure this question is similar to this and this, but I am forced to ask because the solution given there does not work for me:

I added

<property value="true" name="hibernate.id.new_generator_mappings"/>

to my persistence.xml, but to no avail. Any help would be greatly appreciated.

like image 200
Thomas Abraham Avatar asked Feb 14 '17 14:02

Thomas Abraham


People also ask

How does hibernate optimize the performance of the sequence generator?

To avoid this performance penalty (and make the SEQUENCE generator even worth using), Hibernate utilises an optimization where it assumes that it can allocate itself blocks of IDs from the sequence.

How does hibernate use the next value in the identifier sequence?

Before Hibernate performs any inserts of an entity, it will query the database to receive the next value in the identifier sequence. It can then use that value as the ID of the following insert. In terms of SQL, it would look like this:

What is the default hibernate_sequence?

By default, Hibernate will try to work off of a single sequence called hibernate_sequence, so to use the default behaviour, we should create this sequence before running our application (maybe in a migration). This is not too bad and works out of the box.

How does hibernate handle backing database sequence mismatch?

This entire strategy relies on the backing database sequence incrementing in line with Hibernate's expectations. If we have a mismatch and the database sequence increments only by 1, whilst Hibernate expects it to increment by 50, the following happens if we restart the application:


1 Answers

Actually when you migrate to the new Hibernate version 5.2.7, hibernate.id.new_generator_mappings defaults to true.

For backward compatibility you should change this flag to false.

For more information please search the userguide for new_generator_mappings: - http://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html

like image 61
idmitriev Avatar answered Nov 04 '22 17:11

idmitriev