简体   繁体   English

如何更新外键列?

[英]How to update a foreign key column?

I have below tables: 我有下表:

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))

TABLE1 has a MUL key defined with both dept id and dept name. TABLE1具有同时定义了部门ID和部门名称的MUL密钥。 TABLE2 has a Foreign key which references only Dept name from TABLE1 TABLE2有一个外键,仅引用TABLE1中的部门名称

The DTO for TABLE2 gets created like below: TABLE2的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;
   } 

When I try to insert a row in TABLE2, it fails with foreign key constraint violation exception. 当我尝试在TABLE2中插入一行时,由于外键约束冲突异常而失败。

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`))

I also see a EntityExistsException when I debug 调试时也看到EntityExistsException

What is possibly wrong? 可能是什么问题? Is it recommended to refer a part of MUL key as foreign key in another table? 是否建议将MUL密钥的一部分作为另一个表中的外键?

I am using jpa, hibernate, jboss, ejb and mysql 我正在使用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

What is possibly wrong? 可能是什么问题?

This is very clear that, DeptName is foreign key in TABLE2 , which is referring from TABLE1 . 很清楚, DeptNameTABLE2外键,是从TABLE1引用的。 So, you are not allowed to change the value in parent table as the data is being referenced in other table. 因此,不允许在父表中更改该值,因为在其他表中正在引用该数据。

If you are supposed to do this, then you need to alter your table to apply cascade changes to child table as well for your Foreign Key 如果应该这样做,那么您需要更改表以将级联更改也应用于子表以及外键

FOREIGN KEY (DeptName) REFERENCES TABLE1 (DeptName) ON DELETE CASCADE ON UPDATE CASCADE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM