Hello all -
I have a one-to-many association between roles and users. I have created/tested the ORM mappings using Hibernate and successfully persisted instances of both classes. Below are simplified definitions of the classes:
Code:
/**
* A role defines a unique set of users.
*/
public class Role{
private int id;
private String name;
private Set users;
public void setId(int id){...}
public int getId(){...}
public void setName(String n){...}
public String getName(){...}
public void setUsers(Set users){...}
public Set getUsers(){...}
public boolean equals(Object other) {
if(this == other) return true;
if(!(other instanceof Role) ) return false;
final Role a = (Role)other;
if(a.getId() != getId()) return false;
if(!a.getName().equals(getName())) return false;
return true;
}
public int hashCode(){
int hash = 3;
return hash * getName().hashCode();
}
}
/**
* User overrides the equals() and hashCode() method
* using business propertie - should be used when invoking contains().
*/
public class User{
private String id;
public void setId(String id){...}
public String getId(){...}
public boolean equals(Object other) {
if(this == other) return true;
if(!(other instanceof User) ) return false;
final User a = (User)other;
if(!a.getEid().equals(getEid())) return false;
return true;
}
public int hashCode(){
int hash = 6;
return hash * name.hashCode();
}
}
When I create a junit test and attempt to invoke contains() on the user collection the assertion returns true as expected. Below I have a snippet of code to illustrate:
Code:
/**
* JUnit Test that is successful.
*/
public void testRoleContains(){
Role sysadmin = new Role("sysadmin");
User smith = new User("jsmith123","John","Smith");
sysadmin.addUser(smith);
assertTrue(sysadmin.getUsers().contains(smith)); // returns true.
}
However, when I run another unit test that persists both the user and the role using Hibernate, the assertion fails.
Code:
/**
* JUnit Test. The first assertion passed the 2nd assertion fails.
*/
public void testRoleContainsPersist(){
Transaction tx = HibernateSessionFactory.currentSession().beginTransaction();
Role sysadmin = new Role("sysadmin");
User smith = new User("jsmith123","John","Smith");
sysadmin.addUser(smith);
assertTrue(sysadmin.contains(smith)); // returns true
rdao.makePersistent(sysadmin);
tx.commit();
assertTrue(sysadmin.contains(alcazar)); // returns false
}
Hibernate stresses the importance of overriding the equals() and hashCode() methods using business equality (which is what I've done). However, after I persist these objects, I cannot invoke contains() successfully. I suspect it is my implementation of equals() and/or hashCode(), however, I do not know why. I'm quite frustrated trying to find a solution to this and was hoping you can point me in the right direction. Any feedback is appreciated.
Thanks!
R. Alcazar