GeeCON Prague 2014*
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
Author

contains() and equals() in Hibernate Sets

Ricardo Alcazar
Greenhorn

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.

[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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: contains() and equals() in Hibernate Sets