HIBERNATE  |  Register  | 
      SEARCH: 
   
News 
Features 
Documentation 
   Related Projects 
   External Documentation 
Download 
Forum & Mailinglists 
Support 
JIRA Issue Tracking
Wiki Community Area


JBoss.org



middlegen

JIRA Issue Tracking




      
Documentation > Community Area > Equals and HashCode

Equals and HashCode

Java's Collections and Relational database (and thus Hibernate) relies heavily on being able to distinguish objects in unified way.

In Relational database's this is done with primary keys, in Java we got equals() and hashCode() methods on the objects.

This page tries to discuss the difference strategies there exist in making the primary key generation strategy, equals() and hashCode() implementation to work together in harmony.

Why is equals() and hashcode() important

It's quite simple:

1. It is a requirement for objects being stored and retrieved correctly in Java Collections

2. Hibernate (and almost any other app) is using Java Collections

Thus, if you want to store an object in a List, Map or a Set then it is an requirement that equals and hashCode are implemented so they obey the standard contract as specified in the documentation - otherwise Hibernate will not work properly.

It's bothersome to write these methods, can't Hibernate help ?

Well, the only "helping" hand Hibernate can provide is hbm2java. hbm2java

generates a default implementation of equals() and hashcode().

This default generation requires that there is a set of attributes that

is marked as an id. Then if there is an id in the object, the equals and hashcode method will work.

What if I don't have an id attribute ?

Then currently you will have to implement your own equals/hashcode method.

In the future we might provide a feature in hbm2java that allows you to mark which properties should be used when not having an id attribute.

I got an id which is assigned or native, is there any problem about that ?

Yes - sometimes. With assigned and native id's in Hibernate, objects might first get their id's AFTER they have been persisted. This can be a problem if you add e.g. a child object to a parent's children set before you save the child. Here the standard equals and hashcode methods won't provide a consistent answer as they don't have any value assigned to the id attribute. Thus here you also should provide your own implementation of equals and hashcode.

Any best practicies for equals and hashcode

Read the links in 'Background material' and the API docs - they provide the gory details.

Furthermore I encourage anyone with information and tips about equals and hashcode implementations to come forward and show their "patterns" - I might even try to incorporate them inside hbm2java to make it even more helpful ;)

Background material:

Effective Java Programming Language Guide, sample chapter about equals() and hashCode()

Java theory and practice: Hashing it out, Article from IBM

      

coWiki web collaboration