1. 程式人生 > >執行SQL語句的時候唯一約束欄位異常Duplicate entry '33382-1-0' for key xxx

執行SQL語句的時候唯一約束欄位異常Duplicate entry '33382-1-0' for key xxx

前言:做專案的時候,執行SQL語句報了Duplicate entry '33382-1-0' for key xxx異常,後來發現是唯一約束導致,於是乎一通谷歌百度,後來解決了,記錄一下。

正文:

程式碼片段是這樣的:

session.createSQLQuery("insert ignore student_task_trace (student_id,task_plan_id,task_plan_reads_options_id,question_count,finish_count,creation_time,modify_time) " +
							"select s.id,:taskPlanId,:planReadsOptionsId,:questionCount,0,NOW(),NOW() from student as s where s.clazz_id in :clazzIdList")
					.setParameter("taskPlanId", taskPlanId).setParameter("planReadsOptionsId",tproId)
					.setParameter("questionCount", count).setParameterList("clazzIdList", clazzIds).executeUpdate();

可以看到涉及到資料庫的表是student_task_trace 。

表的結構式這樣的:

看的出來不僅主鍵id做了唯一約束,student_id,task_plan_reads_options,sub_type這三個欄位做了聯合約束,也就是說這三個不能有相同的另一條資料,所以在遇到相同的資料持久化的時候會報異常。

解決方法:

1.使用ignore關鍵字,避免重複插入記錄可以使用:

insert ignore student_task_trace (student_id,task_plan_reads_options_id,sub_type)
VALUES (111111,51,0)

insert into student_task_trace (student_id,task_plan_reads_options_id,sub_type)
VALUES (111111,51,0)

第一條sql執行的時候如果已有相同資料會返回0;

第二條sql執行的時候如果已有相同資料會返回異常,如圖:

2.使用Replace,如果舊記錄與新記錄有相同的值,則在新記錄被插入之前,舊記錄被刪除,存入新紀錄

REPLACE INTO student_task_trace (student_id,task_plan_reads_options_id,sub_type)
VALUES (111111,51,0)

insert into student_task_trace (student_id,task_plan_reads_options_id,sub_type)
VALUES (111111,51,0)

第一條sql執行的時候如果已有相同資料會返回2,因為刪除一條插入一條,主鍵id會變;

第二條sql執行的時候如果已有相同資料會返回異常;

還有其他的解決方案這裡不做說明,如需要可自行谷歌-------“解決資料庫唯一約束插入相同資料問題”。