Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: delete many-to-many association

I have two tables with the many-to-many association.

— DB fragment:

loads
Id
Name

sessions
Id
Date

sessionsloads
LoadId
SessionId

— Hibernate mapping fragments:

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

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?

like image 326
MiKo Avatar asked May 06 '10 18:05

MiKo


1 Answers

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);
}
like image 175
Pascal Thivent Avatar answered Nov 11 '22 10:11

Pascal Thivent