我有以下表格:
create table TABLE1 ( id int(10) unsigned NOT NULL AUTO_INCREMENT, deptId int(11) NOT NULL, DeptName varchar(32) NOT NULL, PRIMARY KEY (id), KEY Dept (deptId, DeptName))
create table TABLE2 ( id int(10) unsigned NOT NULL AUTO_INCREMENT, empId int(11) NOT NULL, DeptName varchar(32) NOT NULL, PRIMARY KEY (id), KEY DeptName (DeptName), CONSTRAINT T2FK FOREIGN KEY (DeptName) REFERENCES TABLE1 (DeptName))
表1有一个定义了dept id和dept name的MUL key。
表2有一个外键,它只引用表1中的部门名称
表2的DTO创建如下:
@org.hibernate.annotations.NotFound(action = org.hibernate.annotations.NotFoundAction.IGNORE)
@javax.persistence.ManyToOne(targetEntity = org.amru.persistence.dto.TABLE1DTOImpl.class, fetch=javax.persistence.FetchType.EAGER)
@javax.persistence.JoinColumn(name = "deptName")
public org.amru.persistence.dto.TABLE1DTO getTABLE1() {
return TABLE1;
}
当我试图在表2中插入一行时,它失败,出现外键约束冲突异常。
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`amru`.`TABLE2`, CONSTRAINT `T2FK` FOREIGN KEY (`DeptName`) REFERENCES `TABLE1` (`DeptName`))
在调试时,我还看到一个
EntityExistsException
可能是什么问题?建议在另一个表中将MUL key的一部分引用为外键吗?
我正在使用jpa、hibernate、jboss、ejb和mysql
最佳答案
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row: a foreign key constraint fails
可能是什么问题?
很明显,
DeptName
是指TABLE2
中的外键。因此,不允许更改父表中的值,因为数据正在其他表中引用。如果您应该这样做,那么您需要更改表以将级联更改应用于子表以及Foreign Key
FOREIGN KEY (DeptName) REFERENCES TABLE1 (DeptName) ON DELETE CASCADE ON UPDATE CASCADE
关于java - 如何更新外键列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48456564/