users@glassfish.java.net

JPA, equals and hashCode

From: Stephen Connolly <stephen.alan.connolly_at_gmail.com>
Date: Fri, 14 Dec 2007 05:47:15 +0000

I'm sure this is a regular question, but I was hoping that some
consensus has been formed.

What is the best practice for equals() and hashCode() methods for
@Entity classes?

Option 1:
Leave as Object.equals and Object.hashCode
+ Less code to write
+ Can add multiple new child entities into a collection
- Could have issues adding persisted entities into a collection if you
manage to get them from different sessions
- Have to search the entire collection with an iterator to check for contents

Option 2:
Use only the @Id annotated fields
+/- These are the identity fields, so logically, they should map to
the concept of identity
- Cannot add multiple new child entities into a collection unless you
use application generated IDs (UUIDs anyone)
+ Will be able to identify persisted entities within a collection even
if you've got them from different sessions (as they will be equal /
have the same hashCode)
+ Checking for presence within a collection is as simple as
collection.contains(new Blah(id)), searching on other fields still
requires an iterator.

Option 3:
Use business key fields
- Application must be coded with logic that these business keys are
immutable... they rarely are actually "immutable"
+/- adding multiple new child entities into a collection depends on
when the business key fields are populated.
+ Will be able to identify persisted entities within a collection even
if you've got them from different sessions (as they will be equal /
have the same hashCode)
+ Checking for presence within a collection is as simple as
collection.contains(new Blah(businessKey)), searching on other fields
still requires an iterator.

Have I missed any options?

FYI, my current preferred option is Option 2, but let's start a good
old healthy flame war over the three (until somebody comes up with
Option 4) techniques.

BTW, I know the spec says things about embedded ids, but I could not
find it say anything about @Id fields and the @Entity's equals and
hashCode

-Stephen