Hibernate:更新DELETE上的多托马尼中介表



我是冬眠的新手,不完全理解如何继续更新中间表。

我之间有两个表:会议和amp;出版物

pojo出版物:

private List<Conference> conferences;
...
 @ManyToMany(targetEntity = Conference.class, cascade = { CascadeType.PERSIST,
      CascadeType.MERGE })
  @JoinTable(name = "publications_conferences", joinColumns = @JoinColumn(name = "Publications_id"), inverseJoinColumns = @JoinColumn(name = "Conferences_id"))
  public List<Conference> getConferences() {
    return conferences;
  }
  public void setConferences(List<Conference> conferences) {
    this.conferences = conferences;
  }

pojo会议:

private List<Publication> publications;
...
@ManyToMany(targetEntity = Publication.class, mappedBy = "conferences")
  public List<Publication> getPublications() {
    return publications;
  }
  public void setPublications(List<Publication> publications) {
    this.publications = publications;
  }

我的桌子"会议"包含重复的记录。我的代码检查两个会议A,B是否具有类似的标题和删除A或B。现在,我想以这种方式更新中介表中的参考文献(因此是记录):

删除会议之前" b&quot":

|Publications_id|Conferences_id
-------------------------------
        c       |       a
        d       |       b        

删除会议之后" d&quot":

|Publications_id|Conferences_id
-------------------------------
        c       |       a
        d       |       a        <----- update reference

我尝试了以下代码:

 if (answer == 2) {
            deleteConferenceQ.setParameter("confId", confIdB);
            for (Publication pubB : publicationsB) {
              publicationsA.add(pubB); 
              pubB.getConferences().add(a);
              session.save(pubB);
            }
            int result = deleteConferenceQ.executeUpdate();
            tx.commit();
      }

,但我收到了org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions。因此,我想知道我的工作是否正确。

编辑#1:我用:

替换了上一个代码

if(answer == 2){

            Iterator<Publication> pubBIter = publicationsB.iterator();
            while (pubBIter.hasNext()) {
              Publication pubB = pubBIter.next();
              pubBIter.remove();
              pubB.getConferences().remove(b);
              b.getPublications().remove(pubB);
              pubB.getConferences().add(a);
              publicationsB.add(pubB);
            }
            session.save(a);
            session.delete(b);
          }

我仍然有 session.save(obj)

的例外

有人可以帮我吗?谢谢

从JPA/Hibernate的角度来看,您甚至不应该考虑加入表。您只需要维护@ManyToMany关系的两侧,并让Hibernate管理数据库。在您的情况下,应该下降以删除一行并从联接表中添加一行。您的代码应该看起来像这样

Publication pub = ...;
Conference confToBeRemoved = ...;
Conference confToBeAdded = ...;
pub.getConferences().remove(confToBeRemoved); // this implies equals() and hashcode() are properly implemented
confToBeRemoved.getPublications().remove(pub); // same here
pub.getConferences().add(confToBeAdded);
confToBeAdded.getPublications().add(pub);
// save all

最新更新