File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Object Relational Mapping and the fly likes contains() and equals() in Hibernate Sets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "contains() and equals() in Hibernate Sets" Watch "contains() and equals() in Hibernate Sets" New topic

contains() and equals() in Hibernate Sets

Ricardo Alcazar

Joined: Oct 28, 2005
Posts: 11
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
I agree. Here's the link:
subject: contains() and equals() in Hibernate Sets
It's not a secret anymore!