开发者

Hibernate: @GeneratedValue(strategy = GenerationType

I am using DB2 for my application. I run some insertion script after creating database. That insertion scri开发者_C百科pt generates records in table with id's given in insertion script.

Suppose for abc table insertion script creates a record with id = 3. As id’s are set to auto generated in hibernate so while saving third record from application I got exception.

        Caused by: com.ibm.websphere.ce.cm.DuplicateKeyException: One or
 more values in the INSERT statement, UPDATE statement, or foreign
 key update caused by a DELETE statement are not valid
 because the primary key, unique constraint or unique
 index identified by "1" constrains table

I am using @GeneratedValue(strategy = GenerationType.AUTO)

What strategy = GenerationType I should use to overcome this problem.


There are issues with certain Databases and Hibernate when you use GenerationType.IDENTITY. Try using a sequence and explicitlly configure everything for it:

@Id
@SequenceGenerator(name = "DEPARTMENT_ID_GENERATOR", sequenceName="department_sequence", allocationSize=100)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "DEPARTMENT_ID_GENERATOR")
@Column(unique = true, nullable = false)
protected Long id;


For DB2 @GeneratedValue(strategy = GenerationType.IDENTITY) should work correctly.


If ids are provided in file then you don't need @GeneratedValue at all as there is no id to generate. And make sure to clean database as @SjB suggested.

Also, without knowing much about DB2, the error message suggests that there may be other violation than just duplicate id on insert. Are there any foreign keys involved?


Nothing works except this query.

alter table TABLE_NAME alter column ID set GENERATED BY DEFAULT RESTART WITH 10000;

DB2 should choose available ID itself but not doing so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜