Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

contains() and equals() in Hibernate Sets

Ricardo Alcazar
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.

* 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");

assertTrue(sysadmin.contains(smith)); // returns true


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.

R. Alcazar
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic