• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

contains() and equals() in Hibernate Sets

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
permaculture is a more symbiotic relationship with nature so I can be even lazier. Read tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic