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

▼魔方 西西 提交于 2019-12-20 12:31:33

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/11653497/generatedvalue-with-strategy-generationtype-auto-generates-repeated-value-after

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!