@GeneratedValue with strategy = GenerationType.AUTO generates a duplicate value after restart

I have a sleep object with an id configured as

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

Creating new items works fine on first launch. But if I restart the application and return the entries, then the next time I try to save this object, hibernate will try to use the same identifier generated when the application was not restarted.

I get an error below, and when I started with the trace parameter, I was able to see that the identifier was reused

* Sleep mode: insert into org_myEntity (entitiyJID, entitityName, id) values ​​(?,?,?) Org.hibernate.util.JDBCExceptionReporter
SQL error: 20000, SQLState: 23505 org.hibernate.util.JDBCExceptionReporter statement was aborted because it would cause a duplicate key value in the unique or primary key constraint or unique index by 'SQL120725164357680' defined in 'TABLE_NAME'. org.hibernate.event.def.AbstractFlushingEventListener
Failed to sync database state with org.hibernate.exception.ConstraintViolationException: failed *

By the way, I am using hibernate 3.3.2.GA, javax.persistance 2.0.0 and the Derby 10.5.1 database

Can anyone understand what might be wrong for my generation and how can I fix it?

+8
annotations hibernate
source share
1 answer

If you use AUTO, Hibernate will choose one of the strategies for creating your identifier. From the reference:

AUTO - an identification column, sequence or table depending on the underlying database.

So, you should see the identifiers being created to see which strategy Derby is using. Although it looks like it resets the generator every time the application restarts. Try to install

 <prop key="hibernate.hbm2ddl.auto">update</prop> 

You could quickly fix this using the sequence generator. How:

 @Id @GeneratedValue(strategy=GenerationType.AUTO, generator="my_seq_gen") @SequenceGenerator(name="my_seq_gen", sequenceName="ENTITY_SEQ") private Long id; 

Where ENTITY_SEQ is the name of the sequence in your database (you create it manually).

+11
source share

All Articles