我的问题与二级缓存的 Hibernate Bi-Directional ManyToMany Updates非常相似
我上课如下图
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
@Entity
public class A{
private int id;
private List<B> listB;
...
@Cache (usage = CacheConcurrencyStrategy.TRANSACTIONAL)
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, targetEntity = B.class)
@JoinTable(name = "A_B", joinColumns = { @JoinColumn(name = "a_id") },
inverseJoinColumns = { @JoinColumn(name = "b_id") })
public List<B> getListB() {
return listB ;
}
}
@Cache (usage = CacheConcurrencyStrategy.TRANSACTIONAL)
@Entity
public class B{
private int id;
private List<A> listA;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, targetEntity = A.class)
@JoinTable(name = "A_B", joinColumns = { @JoinColumn(name = "b_id") }, inverseJoinColumns = { @JoinColumn(name = "a_id") })
public List<a> getListA() {
return listA ;
}
public void addToA(A a) {
a.getListB().add(this);
}
}
正如在多对多关系中所预期的那样,我一直在更新双向关系的双方。
现在我面临的问题是,当我尝试添加/更新集合中的项目时会弹出重复的条目。以下是我用来持久化实体的代码...
b.getA().clear() ;
...
...
b.getListA().add(A) ;
b.addToA(A) ;
em.saveOrUpdate(b) ;
以下是从日志中获取的 Hibernate 触发的查询。
delete from A_B where b_id=?
insert into A_B (b_id, a_id) values (?, ?)
insert into A_B (b_id, a_id) values (?, ?)
delete from A_B where a_id=?
insert into A_B (a_id, b_id) values (?, ?)
insert into A_B (a_id, b_id) values (?, ?)
insert into A_B (a_id, b_id) values (?, ?)
insert into A_B (a_id, b_id) values (?, ?)
我在哪里错了?如何摆脱正在插入的重复项?缓存正在被正确刷新,但重复的条目是唯一的问题!