gpt4 book ai didi

java - @ManyToMany 连接表失败

转载 作者:行者123 更新时间:2023-12-01 05:01:57 26 4
gpt4 key购买 nike

我遇到了一个尚未解决的问题。

环境:

  • MySQL 5
  • 操作系统
  • hibernate 4.1
  • Spring 3.1
  • Spring Data JPA

我有两个处于多对多关系的实体。为此,我使用带有外键的联接表。这是我的实体(为简洁起见进行了修改):

@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

这并不能解决我的问题。

那么有人知道这是命名策略问题还是其他问题吗?

最佳答案

虽然我预计会出现不同的错误,但 JoinColumn 中定义的字段似乎与您在关系表中指定为字段的字段不匹配。尝试修复注释中的联接列以引用“Employee_id”和“Office_id”而不是“EmployeeId”和“OfficeId”。

关于java - @ManyToMany 连接表失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13289388/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com