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. TABLE2 has a Foreign key which references only Dept name from TABLE1
The DTO for TABLE2 gets created like below:
@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.
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
What is possibly wrong? Is it recommended to refer a part of MUL key as foreign key in another table?
I am using jpa, hibernate, jboss, ejb and mysql