Hi.
I have a model where Users can be in many Groups, Users should have a Collection of Groups that they're in, and Groups should have a Collection of Users which are a member of the current group.
Here is my mapping document:
Code:
<class name="com.foo.User" table="USERS">
<id name="id" type="long" unsaved-value="null" column="id">
<generator class="native"/>
</id>
<property name="name" type="string"/>
<property name="password" type="string"/>
<property name="email" type="string"/>
<set name="groups" lazy="true" table="GROUP_USERS">
<key column="user_id"/>
<many-to-many class="com.foo.Group" column="group_id"/>
</set>
</class>
<class name="com.foo.Group" table="GROUPS">
<id name="id" type="long" unsaved-value="null" column="id">
<generator class="native"/>
</id>
<property name="name" type="string"/>
<property name="description" type="string"/>
<set name="users" lazy="true" table="GROUP_USERS">
<key column="group_id"/>
<many-to-many class="com.foo.User" column="user_id"/>
</set>
</class>
I create 2 users and 2 groups, and add both users to both groups:
Code:
User user1 = new User();
user1.setName("user1");
user1.setPassword("password");
user1.setEmail("user1@foo.com");
sess.save(user1);
User user2 = new User();
user2.setName("user1");
user2.setPassword("password");
user2.setEmail("adam@foo.com");
sess.save(user2);
Group group1 = new Group();
group1.setName("test group 1");
group1.setDescription("test group 1 - description");
sess.save(group1);
Group group2 = new Group();
group2.setName("test group 2");
group2.setDescription("test group 2 - description");
sess.save(group2);
Query groupq = sess.createQuery("from com.foo.Group group");
List groups = groupq.list();
for (int i = 0; i < groups.size(); i++) {
Group group = (Group) groups.get(i);
log.debug("Found group: " + group.getName());
Set userSet = group.getUsers();
if (null == userSet) {
userSet = new HashSet();
}
Query userq = sess.createQuery("from com.foo.User user");
List users = userq.list();
for (int j = 0; j < users.size(); j++) {
User user = (User) users.get(j);
log.debug("Adding user: " + user.getName() + " to group: " + group.getName());
userSet.add(user);
}
group.setUsers(userSet);
sess.saveOrUpdate(group);
sess.flush();
}
Now in another method, using the same Hibernate Session:
Code:
Query userq = sess.createQuery("from com.foo.User user");
List users = userq.list();
for (int i = 0; i < users.size(); i++) {
User user = (User) users.get(i);
Set groups = user.getGroups();
if (null == groups) {
log.debug("user: " + user.getName() + " does not seem to be in any groups");
}
else {
for (Iterator iterator = groups.iterator(); iterator.hasNext();) {
Group group = (Group) iterator.next();
log.debug("user: " + user.getName() + " is in group: " + group.getName());
}
}
}
And the User never seems to have a Set which contains the Group's that the User is in.
Any ideas?
-Ian.