Java – Hibernate: delete many to many associations

I have two tables associated with many to many

– DB segment:

Load ID name

Meeting Id date

sessionsloads LoadId SESSIONID

– hibernate mapping fragment:

/* 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>

To delete an entry from the association table sessionsloads, I execute this Code:

Session session = sessionDao.getObject(sessionId);
Load load = loadDao.getObject(loadId);

load.getSessions().remove(session);
loadDao.saveObject(load);

However, nothing has changed since startup

What is the correct way to delete an association?

Solution

You need to update both ends 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);

In fact, many developers use a defensive approach to manage two - way relationships For example, in load, you can 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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>