How does EclipseLink use equals() and hashCode()? [message #787124] |
Tue, 31 January 2012 02:26  |
Eclipse User |
|
|
|
I'm thinking about how to implement equals and hashCode in my entities. What requirements does EclipseLink have for these methods? Does it use them internally?
I found a discussion at stackoverflow (question 6534721, "equals-and-hashcode-for-jpa-entities-using-eclipselink") where James suggests that EclipseLink does not use equals and hashCode internally and won't be broken by their implementations. Is this really correct? Another post (dev.eclipse.org -> mhonarc/lists/eclipselink-users/msg02241.html) seems to suggest that it is not that simple: "EclipseLink generally has no dependencies on equals and hashCode unlike other JPA providers, but we still require to be able to remove objects from collections, and that requires that the hashCode and equals are at least correctly implemented. (James Sutherland)"
(sorry, cant post links until I have posted more than 5 messages.)
- one option would be to implement equals based on primary key. In this case hashCode can change while entity is stored in a set (when a new entity gets persisted and primary key is changed from null to some value). Would this break something inside eclipselink?
At a quick look I did not find a mention about implementing equals/hashCode in the JPA specification. Doesn't this mean that I should be able to create my custom equals/hashCode methods freely without worrying about the JPA implementation? Or what would this
public int hashCode() {
return random.nextInt(255);
}
break?
Of course I need to take into consideration how equals/hashCode implementations affect my application code, but now I'm interested in what happens in the JPA stack.
|
|
|
Re: How does EclipseLink use equals() and hashCode()? [message #789193 is a reply to message #787124] |
Thu, 02 February 2012 13:14  |
Eclipse User |
|
|
|
EclipseLink has no specific dependencies on equals and hashCode. You can use the default Object implementation, or your own.
If you use an equals/hashCode that is plain wrong, then you can have issues with Java in general in using your objects in Maps and Collections and other places. These can affect your persistence, as if you use a List, Set or Map in your object model, and for instance implement your brilliant random hashCode, then your Maps and Sets will not work correctly. If you implement a similarly brilliant equals, then Lists will not work correctly.
|
|
|
|
Powered by
FUDForum. Page generated in 0.19378 seconds