存在持续单向 @ManyToMany 关系的问题。我将 EclipseLink 2.3 与 Spring 数据和 MySQL 一起使用。
实体伪代码:
@Entity
public class Subscriber {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private List<SubscribersList> subscribersLists;
//...shortened...
}
@Entity
public class SubscribersList {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
//...shortened...
}
接下来在某些服务中,我创建新列表和两个订阅者...
list = new SubscribersList("DEFAULT");
s1 = new Subscriber();
s1.getSubscribersList().add(list); //empty list is created in the constructor
repository.save(s1); //works ok
s2 = new Subscriber();
s2.getSubscribersList().add(list);
repository.save(s2); //fails with Duplicate entry '2' for key 'PRIMARY'
保存第一个订阅者后,列表成为托管实体,但尽管如此保存第二个订阅者 JPA 尝试再次创建列表:
Call: INSERT INTO SUBSCRIBERSLIST (ID, DESCRIPTION, TITLE) VALUES (?, ?, ?)
bind => [2, null, DEFAULT]
有趣的是,我与内存 hsqldb 的集成测试有效。显然我错过了一些东西,但无法发现问题......