I have an entity user which has a many-to-many association with itself
a User is a tenant to a List<User> a User is a Renter to a List<User>
I load a Renter, and I initialize its List<Tenant> Then at some point he wants to remove oneself from the Tenant, so I have this function:
public void removeOneselfFromTenant(User tenant, User oneself) { // initialize Tenant List<Renter>, as it is lazy loaded getSessionFactory().getCurrentSession().lock(tenant, LockMode.NONE); Hibernate.initialize(tenant.getRenterList());
// remove the association from both sides tenant.getRenterList().remove(oneself); oneself.getTenantList().remove(tenant); // update the Renter who is mapping the association getSessionFactory().getCurrentSession().update(oneself); }
But I get a org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
which makes sense I believe, because when initializing the Tenant List<Renter>, I load the List<Renter>, which contains the same record from the Renter already present (oneself) they are different object, but they correspond to the same record (thus the same id)
so I don't know what I should do, I understand that to delete the association, I need to delete the Tenant from the Renter collection; and the opposite I guess that I should do something like loading all List<Renter> in the Tenant object EXCEPT the Renter which already exists in the session (oneself)
Is there a better way I'm supposed to do?
Thanks!
|