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

1

11

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?

Agiotage answered 25/7, 2012 at 15:39 Comment(0)
S
16

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).

Skipper answered 25/7, 2012 at 17:4 Comment(1)
It was a bit more tricky, but your remark to the "hibernate.hbm2ddl.auto" ringed the bell. I finally had one project properties file with the hibernate.hbm2ddl.auto set to create-drop and the SessionFactory of one of the bundles with the hibernate.hbm2ddl.auto set to update. So that was causing my data for that bundle to be kept on the database, but the iterators to be restarted. Obrigado pela dica =DAgiotage

© 2022 - 2024 — McMap. All rights reserved.