Ilias Stavrakis
Ilias Stavrakis

Reputation: 753

How entity manager uses hashcode and equals in JPA

I have a standard JEE application with JPA. While merging previously detached entities does entity manager uses equals or hashcode to find if the object I merge is already managed? Generally when entity manager uses hashcode or equals? Is this affected by the JPA engine I use, for example Hibernate or Eclipse Link?

Upvotes: 0

Views: 850

Answers (2)

To calculate the state of an entity Hibernate uses Dirty checking.

With dirty checking

By default Hibernate checks all managed entity properties. Every time an entity is loaded, Hibernate makes an additional copy of all entity property values. At flush time, every managed entity property is matched against the loading-time snapshot value.

The dirty checking is performed by checking all property values saved at loading time.

There is no relation of equals and hashcode with how entitymanager works internally in Hibernate.

Upvotes: 2

Chris
Chris

Reputation: 21145

This is implementation dependent, but using your Entity hashcode or equals methods would not be all that reliable for any JPA mechanism. EclipseLink does not use your equals or hashcode implementation to perform lookups or comparisons - it will use the System.identityHashCode when a hashcode is need.

An incorrect or inefficient hashcode and equality method will still have adverse affects on your application though, especially in mappings that use collection types. I'd recommend you not override them without some great need.

Upvotes: 0

Related Questions