我在两个实体之间有一个@ManyToMany 关系。当我在拥有方执行更新时,JPA 似乎从我的数据库中删除了所有链接记录并重新插入它们。对我来说这是个问题,因为我有一个 MySQL 触发器在删除记录之前触发。关于如何解决这个问题的任何想法?
@Entity
public class User {
@Id
@Column(name="username")
private String username;
...
@ManyToMany
@JoinTable(name="groups", joinColumns=
@JoinColumn(name="username", referencedColumnName="username"),
inverseJoinColumns=@JoinColumn(name="groupname",
referencedColumnName="type_id"))
private List<UserType> types;
...
}
@Entity
public class UserType {
@Id
@Column(name="type_id")
private String id;
@ManyToMany(mappedBy="types")
private List<User> users;
...
}
最佳答案
使用 Set
而不是 List
解决了这个问题。但我不知道它为什么有效。
Hibernate 提供的另一种解决方案是将@ManyToMany
关联拆分为两个双向@OneTo@Many
关系。参见 Hibernate 5.2 documentation例如。
If a bidirectional
@OneToMany
association performs better when removing or changing the order of child elements, the@ManyToMany
relationship cannot benefit from such an optimization because the foreign key side is not in control. To overcome this limitation, the link table must be directly exposed and the@ManyToMany
association split into two bidirectional@OneToMany
relationships.
关于java - JPA更新多对多删除记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3504371/