Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

contains() and equals() in Hibernate Sets

 
Ricardo Alcazar
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:



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:



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
}
/CODE]

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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic