gpt4 book ai didi

java - hibernate : Update many-tomany intermediary table on Delete

转载 作者:行者123 更新时间:2023-12-01 11:33:20 25 4
gpt4 key购买 nike

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

我在两个表之间有多对多关系: session 和出版物

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

我的表“conferences”包含重复的记录。我的代码检查两个 session a,b 是否具有相似的标题并删除 a 或 b。现在,我不想删除中间表中的引用(以及记录),而是想以这种方式更新它:

删除 session “b”之前:

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

删除 session “d”后:

|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:非法尝试将集合与两个打开的 session 关联。因此我想知道我的做法是否正确。

编辑#1:我用以下代码替换了以前的代码:

如果(答案==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

关于java - hibernate : Update many-tomany intermediary table on Delete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30240981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com