Hi,
I have 2 POJO classes (Event and Plan):
Code:
@Entity
@Table(name="T_EVENT")
public class Event {
private List<Plan> plans;
// ... truncated
@ManyToMany(
fetch=FetchType.LAZY,
cascade={CascadeType.PERSIST, CascadeType.MERGE}
)
@JoinTable(
name="T_EVENT_PLAN",
joinColumns={@JoinColumn(name="EVENT_ID")},
inverseJoinColumns={@JoinColumn(name="PLAN_ID")}
)
public List<Plan> getPlans() {
return plans;
}
public void setPlans(List<Plan> plans) {
this.plans = plans;
}
}
@Entity
@Table(name="T_PLAN")
public class Plan {
// ... truncated
}
They are associated to each other with many-to-many relation. I want to modify the list of plans for given event. The event and the plans I want to associate are objects loaded via Hibernate but
dettached from the session they were loaded from. I use the following code in a new session:
Code:
// consider `event' and `plan' are detached instances from another session; `session' is current Hibernate Session
List<Plan> plans = new ArrayList<Plan>();
plans.add(plan);
event.setPlans(plans);
session.getTransaction().begin();
session.merge(event);
session.getTransaction().commit();
The problem I encounter is that the assosiated plans aren't persisted. No exception is thrown either, nor I see DELETE/INSERT statements association table. If I explictly reattach the `event' object to the current session using:
Code:
session.lock(event, LockMode.NONE);
it works just fine.
My questions is why doesn't "merge" perist the collection I pass but requires explicit reattachment?
The odd thing is if I change the code to:
Code:
event.getPlans().clear();
event.getPlans().add(plan);
session.getTransaction().begin();
session.merge(event);
session.getTransaction().commit();
it works just fine. It seems that setting new ArrayList causes a problem.
Another observation is that refreshing the detached `event' object fixes the problem.
If someone can point me to what I'm missing to understand the real source of the problem?
I'm using "Hibernate Annotations 3.2.0" in JSF application (MyFaces) on JDK 1.5.0.9/Windows.
Thank you in advance!