Hibernate: delete many-to-many association

青春壹個敷衍的年華 提交于 2019-12-02 21:08:36

You need to update both sides of the link between Load and 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:

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

Looks like you just need to turn on Transitive persistence (e.g., cascade=all-delete-orphan for "full" transitive.)

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

--

Also, an Entity named Session broke my brain :(

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!