2011-10-12 94 views
0

我使用DB2为我的应用程序创建数据库后,运行一些插入脚本插入脚本表生成记录在插入脚本给定id的休眠:@GeneratedValue(策略= GenerationType

假设为ABC表。插入脚本创建具有ID的记录= 3的ID设置为休眠自动生成所以虽然从应用程序中保存的第三个记录我的异常。

 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 

我使用@GeneratedValue(strategy = GenerationType.AUTO)

什么strategy = GenerationType我应该用来克服这个问题。

+0

您必须在插入此规则后清除数据库 – SjB

+0

@SjB插入哪个规则后? –

回答

0

除此查询外没有任何工作。

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

DB2应该自己选择可用的ID,但不这样做。

0

对于DB2 @GeneratedValue(strategy = GenerationType.IDENTITY)应该正常工作。

+0

它没有工作。 –

0

如果在文件中提供了id,那么根本就不需要@GeneratedValue,因为没有id要生成。并确保清理数据库为@SjB建议。另外,在不了解DB2的情况下,错误消息表明可能存在其他冲突,而不仅仅是插入时的重复ID。是否有外键参与?

1

当您使用GenerationType.IDENTITY时,某些数据库和Hibernate存在问题。尝试使用一个序列,并明确地配置它的一切:

@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;