MySQL外键约束冲突异常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (...)

异常内容

Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`book`.`t_order`, CONSTRAINT `t_order_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`))

外键约束冲突,我的错误出在插入的 id 已经存在了,所以产生了冲突。

外键联系的两个表之间存在依赖关系,主表的还没有的时候,从表自然也不能存在(这就是约束,主键要消失,你下面有从表——不行;从表要新增,你联系的那个主表还没创建——不行)。就像没你老子就没你,同理你老子还没出生,你就要蹦出来,自然也是不行

此问题关键是错误消息出现在数据库上,所以排错方向也应该在此。

又一个场景,删除存在外键约束的表数据时,异常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

解决办法:

#存在外键约束的表数据无法被删除,删除前需要先删除外键约束
SET foreign_key_checks = 0;-- 删除外键约束
truncate table t_order;
truncate table t_order_item;
SET foreign_key_checks = 1;-- 启动外键约束
原文地址:https://www.cnblogs.com/csyh/p/13518308.html