MyBatis添加数据报错Cannot add or update a child row: a foreign key constraint fails

报错信息:

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,就解决了。

 

 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值