java Hibernate:删除多对多关联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2783602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate: delete many-to-many association
提问by 0x2D9A3
I have two tables with the many-to-many association.
我有两个多对多关联的表。
— DB fragment:
— 数据库片段:
loads
Id
Name
加载
ID
名称
sessions
Id
Date
会话
ID
日期
sessionsloads
LoadId
SessionId
会话
加载 LoadId
SessionId
— Hibernate mapping fragments:
— Hibernate 映射片段:
/* loads.hbm.xml */
<set name="sessions" table="sessionsloads" inverse="true">
<key column="LoadId" />
<many-to-many column="SessionId" class="Session" />
</set>
…
/* sessions.hbm.xml */
<set name="loads" table="sessionsloads">
<key column="SessionId" />
<many-to-many column="LoadId" class="Load" />
</set>
In order to remove one entry from the association table sessionsloads, I execute this code:
为了从关联表sessionloads 中删除一个条目,我执行以下代码:
Session session = sessionDao.getObject(sessionId);
Load load = loadDao.getObject(loadId);
load.getSessions().remove(session);
loadDao.saveObject(load);
But, after launching, this code change nothing.
但是,启动后,此代码没有任何改变。
What's the right way to remove an association?
删除关联的正确方法是什么?
回答by Pascal Thivent
You need to update both sides of the link between Loadand Session:
您需要更新Load和之间的链接的双方Session:
Session session = sessionDao.getObject(sessionId);
Load load = loadDao.getObject(loadId);
load.getSessions().remove(session);
session.getLoads().remove(load);
loadDao.saveObject(load);
Actually, many developer use defensive methods to manage bi-directional associations. For example on Load, you could add the following methods:
实际上,许多开发人员使用防御方法来管理双向关联。例如Load,您可以添加以下方法:
public void removeFromSessions(Session session) {
this.getSessions().remove(session);
session.getLoads().remove(this);
}
public void addToSessions(Session session) {
this.getSessions().add(session);
session.getLoads().add(this);
}
回答by Affe
Looks like you just need to turn on Transitive persistence (e.g., cascade=all-delete-orphan for "full" transitive.)
看起来你只需要打开传递持久性(例如,cascade=all-delete-orphan 表示“完全”传递。)
-- Edit Thanks for the upvote, althugh Pascal was accurate in that cascade alone is not enough to fix the original problem, but that both sides of the relationship weren't being managed. Teach me to answer hastily :)
-- 编辑 感谢您的支持,尽管 Pascal 是准确的,仅靠级联不足以解决最初的问题,但双方关系都没有得到管理。赶紧教我回答:)
--
——
Also, an Entity named Session broke my brain :(
此外,一个名为 Session 的实体打破了我的大脑:(

