报错信息:
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,就解决了。