There have been some discussions here about JPA entities and which hashCode()
/equals()
implementation should be used for JPA entity classes. Most (if not all) of them depend on Hibernate, but I'd like to discuss them JPA-implementation-neutrally (I am using EclipseLink, by the way).
All possible implementations are having their own advantages and disadvantages regarding:
hashCode()
/equals()
contract conformity (immutability) for List
/Set
operationsAs far I can see, there are three options:
Object.equals()
and Object.hashCode()
hashCode()
/equals()
workhashCode()
/equals()
are brokenhashCode()
/equals()
are brokenMy questions are:
UPDATE 1:
By "hashCode()
/equals()
are broken", I mean that successive hashCode()
invocations may return differing values, which is (when correctly implemented) not broken in the sense of the Object
API documentation, but which causes problems when trying to retrieve a changed entity from a Map
, Set
or other hash-based Collection
. Consequently, JPA implementations (at least EclipseLink) will not work correctly in some cases.
UPDATE 2:
Thank you for your answers -- most of them have remarkable quality.
Unfortunately, I am still unsure which approach will be the best for a real-life application, or how to determine the best approach for my application. So, I'll keep the question open and hope for some more discussions and/or opinions.
Read this very nice article on the subject: Don't Let Hibernate Steal Your Identity.
The conclusion of the article goes like this:
Object identity is deceptively hard to implement correctly when objects are persisted to a database. However, the problems stem entirely from allowing objects to exist without an id before they are saved. We can solve these problems by taking the responsibility of assigning object IDs away from object-relational mapping frameworks such as Hibernate. Instead, object IDs can be assigned as soon as the object is instantiated. This makes object identity simple and error-free, and reduces the amount of code needed in the domain model.