Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a hibernate entity with an ID configured as

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

The creation of new elements works ok in the first run. But if I restart my application and retrieve back the records, the next time I try to persist this entity, hibernate tries to use the same ID generated when the application was not restarted.

I get the error below, and when running with trace option, I was able to see that the ID was being reused

*Hibernate: insert into org_myEntity (entitiyJID, entitityName, id) values (?, ?, ?) org.hibernate.util.JDBCExceptionReporter
SQL Error: 20000, SQLState: 23505 org.hibernate.util.JDBCExceptionReporter The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL120725164357680' defined on 'TABLE_NAME'. org.hibernate.event.def.AbstractFlushingEventListener
Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: could not*

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

Does someone have any idea what could be wrong on my generation and how could I fix it?

like image 254
Thomas Avatar asked Jul 25 '12 15:07

Thomas


1 Answers

If you use AUTO, Hibernate will choose one of the strategies to generate your id. From the Reference:

AUTO - either identity column, sequence or table depending on the underlying DB.

So you have to see the ids being generated to see which strategy Derby is using. Although it looks like, it resets the generator everytime you restart your app. Try setting

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

You could quickly fix it using a sequence generator though. Like:

@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 one manually).

like image 137
Tiago Farias Avatar answered Sep 28 '22 05:09

Tiago Farias