我的问题非常类似于这个
Hibernate Bi-Directional ManyToMany Updates with Second Level cache
我上课了,如下所示
@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,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) ;
delete from A_B where b_id=? insert into A_B (b_id,a_id) values (?,?) insert into A_B (b_id,?) delete from A_B where a_id=? insert into A_B (a_id,b_id) values (?,?) insert into A_B (a_id,?)
我在哪里错了?
如何摆脱正在插入的重复项?
缓存正在正确刷新,但重复的条目是唯一的问题!