我遇到了一个我尚未能解决的问题。
环境:
我在ManyToMany关系中有两个实体。我使用带有外键的Join表。 以下是我的实体(为简洁起见而修改):
@Entity
public class Employee {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
private Long employeeId;
@ManyToMany( cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = Office.class )
@JoinTable( name = "EmployeeOfficeJoin", joinColumns = { @JoinColumn( name = "EmployeeId", nullable = false, updatable = false ) }, inverseJoinColumns = { @JoinColumn( name = "OfficeId", nullable = false, updatable = false ) } )
private List<Office> offices = new ArrayList<Office>();
}
和
@Entity
public class Office {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
private Long officeId;
@ManyToMany( mappedBy = "offices", targetEntity = Employee.class, fetch = FetchType.EAGER )
private List<Employee> employees = new ArrayList<Employee>();
我的联接表是:
CREATE TABLE IF NOT EXISTS `dental`.`EmployeeOfficeJoin` (
`EmployeeId` BIGINT(11) ,
`OfficeId` BIGINT(11),
PRIMARY KEY ( `employeeId`, `officeId` ),
FOREIGN KEY ( `employeeId` ) REFERENCES `Employee` (`EmployeeId` ),
FOREIGN KEY ( `officeId` ) REFERENCES `Office` ( `Officeid` ) )
ENGINE = InnoDB
我正在使用这个命名:
hibernate.ejb.naming_strategy=org.hibernate.cfg.DefaultNamingStrategy
当我尝试使用它时:
Employee emp = new Employee();
...
emp.getOffices().add(newOffice);
employeeRepository.save(emp);
失败前的最后一个插入语句是:
Hibernate:
insert
into
EmployeeOfficeJoin
(EmployeeId, OfficeId)
values
(?, ?)
TRACE - BasicBinder - binding parameter [1] as [BIGINT] - 1
TRACE - BasicBinder - binding parameter [2] as [BIGINT] - 1
DEBUG - SqlExceptionHelper - Cannot add or update a child row: a foreign key constraint fails (`dental`.`employeeofficejoin`, CONSTRAINT `employeeofficejoin_ibfk_1` FOREIGN KEY (`EmployeeId`) REFERENCES `Employee` (`EmployeeId`)) [n/a]
看来案例全部改变了,我看到someone认为这可能是OS X问题上的MySQL。但是当我使用
时hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
它并没有为我解决。
所以有人知道这是一个命名策略问题还是别的什么?
答案 0 :(得分:0)
我希望有一个不同的错误,但JoinColumn中定义的字段似乎与您在关系表中指定的字段不匹配。尝试修复注释中的连接列以引用“Employee_id”和“Office_id”而不是“EmployeeId”和“OfficeId”。