I was calling remove() on the collection. My test case showed that the collection was empty but the table wasn't.
I've tried another angle on this, by creating an object to map the many-to-many-to-many relation as it's own entity:
Code:
@Entity
@IdClass(BusinessUserRole.class)
public class BusinessUserRole implements Serializable {
private static final long serialVersionUID = -5848868659114816920L;
Business business;
User user;
Role role;
// ... getters, setters follow ...
And in Business:
Code:
Set<BusinessUserRole> userRoles = new HashSet<BusinessUserRole>();
@OneToMany
public Set<BusinessUserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<BusinessUserRole> userRoles) {
this.userRoles = userRoles;
}
public void addRoleForUser(User u, Role role) {
BusinessUserRole bur = new BusinessUserRole(this, u, role);
userRoles.add(bur); // Does nothing if it is already there
}
public void removeRoleForUser(User u, Role role) {
BusinessUserRole bur = new BusinessUserRole(this, u, role);
userRoles.remove(bur);
}
When when I remove all roles for a user, the table is empty.
However, now my queries are somewhat inefficient:
Code:
public Set<Role> getRolesForUser(User u) {
Set<Role> result = new HashSet<Role>();
for(BusinessUserRole bur: userRoles) {
if(bur.getUser().equals(u))
result.add(bur.getRole());
}
return result;
}
It seems like I may not have the expressive power I need here - I probably need to roll this into the DAO so that I can do this as a query instead, I guess.
Is there a way to map the same table into multiple collections which can be lazily fetched?
[/code]