2011-10-12 90 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;