Hibernate:在删除

时间:2015-05-14 15:18:08

标签: java hibernate many-to-many

我对Hibernate相当新,并且不完全理解我应该如何继续更新中间表。

我在两个表之间有一个ManyToMany关系:conference&出版物

POJO Publication.class:

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 Conference.class:

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;
  }

我的桌子&#34;会议&#34;包含重复的记录。我的代码检查两个会议a,b是否有相似的标题并删除a或b。现在,我想以这种方式更新它,而不是删除中间表中的引用(以及记录):

删除会议之前&#34; b&#34;:

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

删除会议&#34; d&#34;:

|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)

上有上一个例外

任何人都可以帮助我吗?感谢

1 个答案:

答案 0 :(得分:1)

从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