MyBatis新增資料報錯Cannot add or update a child row: a foreign key constraint fails
阿新 • • 發佈:2021-02-07
技術標籤:java後端資料庫javamysqlsqlmybatis
報錯資訊:
org.springframework.dao.DataIntegrityViolationException: ### Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`ssm_crud`.`tbl_emp`, CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`)) ### The error may exist in file [C:\Users\SAMSUNG\IdeaProjects\SSMProject\target\classes\resources\mapper\EmployeeMapper.xml] ### The error may involve com.hup.dao.EmployeeMapper.insertSelective-Inline ### The error occurred while setting parameters ### SQL: insert into tbl_emp ( emp_name, gender, email, d_id ) values ( ?, ?, ?, ? ) ### Cause: java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`ssm_crud`.`tbl_emp`, CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`)) ; Cannot add or update a child row: a foreign key constraint fails (`ssm_crud`.`tbl_emp`, CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`)); nested exception is java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`ssm_crud`.`tbl_emp`, CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`))
問題出在外來鍵約束上:
先給大家介紹我的資料庫,這是員工庫:
這是部門庫:
可以看出,它們是由員工庫的部門編號d_id和部門庫的部門編號dept_id連線起來的,也可以看出,我先添加了兩個部門,編號分別是4和5(索引是自增的,我沒注意到),這時我想新增員工,可是我把員工的部門編號寫成了1,部門庫中是沒有這個索引的!就匹配不上了,就出現了上述報錯資訊。。
因此,不是coding問題,是新增資料的時候要注意~
我把部門編號改成了1和2,就解決了。