I have 2 Hibernate objects Group and User which are related with a ManyToMany relationship.
I use the following mapping
Group.java
private Set<User> users = new HashSet<User>(0);
...
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_group",
joinColumns = { @JoinColumn(name = "GROUP_ID") },
inverseJoinColumns = { @JoinColumn(name = "USER_ID") })
public Set<User> getUsers() {
return this.users;
}
...
User.java
private Set<Group> groups = new HashSet<User>(0);
...
@ManyToMany(mappedBy = "users")
public Set<Group> getGroups() {
return this.groups;
}
...
DAO.java
public User addUserToGroup (Integer groupId , Integer userId){
Group group = (Group) getBeanById(groupId, Group.class); //Here I get the right group
User user = (User) getBeanById(userId, User.class);//Here I get the right user
group.getUsers().add(user);
user.getGroups().add(group);
save(group);
return user;
}
The save method
public EntityBase save(EntityBase transientInstance) {
Session session = HibernateUtil.getCurrentSession();
log.debug("persisting instance");
try {
session.saveOrUpdate(transientInstance);
log.debug("persist successful");
return transientInstance;
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
My problem is when I add a user to a groupe, no record is added to the association table user_group.
NB : The begin and commit statements are called in a filter Servlet
The code above does what it should do.
My problem was at the display of the list of the users, Hibernate detect a dirty users collections and delete it. What I ended up doing is to change the ownership of the relationship to Group instead of the User, and all behaved normally.