I have a class 'User' and a class 'Group'. Each user has many groups and group has many users. What is the best way to set this relationship up such that the Group.users collection is automatically updated when a User is deleted?
For example, assume the following group is setup.
Code:
// Add users to a group
User tom = getUser("tom");
User joe = getUser("joe");
Group test = getGroup("test");
test.getUsers().add(tom);
test.getUsers().add(joe);
session.save(test);
Later in time, remove a user. What I would like is to automatically update the test.users collection such that tom is removed. Is this possible? Or am I supposed to manage the test.users collection and explicitly remove tom from the collection before trying to delete that User?
Code:
User tom = getUser("tom");
session.delete(tom);
At the moment using the collection mapping given below, when I try to delete this object a ConstraintViolationException is generated as the foreign key is violated
Code:
Integrity constraint violation FK25560AA4876FD071 table: GROUPUSERS_USER_SET in statement [/* delete org.pcj.model.User */ delete from Users where ID=? and Version=?]
The mapping is given below:
Code:
<class name='Group' table='Groups' dynamic-insert='true' dynamic-update='true' optimistic-lock='version'>
<id name='Id' column='ID'>
<generator class='native'/>
</id>
<natural-id mutable='false'>
<property name='Name'/>
</natural-id>
<version name='Version'/>
<property name='Description'/>
<set name='Users' table='GroupUsers_User_set' cascade='all'>
<key column='GroupUsers_ID'/>
<many-to-many class='User' column='User_ID'/>
</set>
</class>