JPA 数据库添加数据报错Cannot add or update a child row a foreign key constraint fails
First Post:
Last Update:
Last Update:
JPA 数据库添加数据报错:Cannot add or update a child row: a foreign key constraint fails
jpa单表操作 ,出现的错误
1 | java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`dj_examination_service`.`dj_exam_bank_rules`, CONSTRAINT `dj_exam_bank_rules_ibfk_1` FOREIGN KEY (`question_bank_id`) REFERENCES `dj_exam_question_bank` (`id`)) |
网上的帖子是说对应的主键不存在,但是我的数据库中明明是早已就创建好的。
这时候查看sql输出内容发现端倪。insert 的值 反了,最终找到配置多对多关系的时候 对应的id写反了
实体SelectionRules 中错误的配置
正确配置 如下
1 | @ManyToMany |
报错的原因大概分为三种:
原因一:
添加的外键列与另一个表的唯一索引列(一般是主键)的数据类型不同
原因二:
要添加外键的表类型与另一个表的存储引擎是不是都为innodb引擎
#查看表引擎
法一: show create table 表名;
法二:show table status from 数据库 where name=‘表名’;
法三:use information_schema;
select table_catalog,table_schema,table_name,engine from tables
where table_schema=‘数据库名’ and table_name=‘表名’;
原因三:
设置的外键与另一个表中的唯一索引列(一般是主键)中的值不匹配
#解决办法:删除要成为外键的列,再次创建并默认为NULL
打赏
支付宝 | Alipay


微信 | WeChat

