How should equals and hashcode be implemented when using JPA and Hibernate

Viewed 63677

How should model class's equals and hashcode be implemented in Hibernate? What are the common pitfalls? Is the default implementation good enough for most cases? Is there any sense to use business keys?

It seems to me that it's pretty hard to get it right to work in every situation, when lazy fetching, id generation, proxy, etc are taken into account.

8 Answers

In the documentation of Hibernate 5.2 it says you might not want to implement hashCode and equals at all - depending on your situation.

https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#mapping-model-pojo-equalshashcode

Generally, two objects loaded from the same session will be equal if they are equal in the database (without implementing hashCode and equals).

It gets complicated if you're using two or more sessions. In this case, the equality of two objects depends on your equals-method implementation.

Further, you'll get into trouble if your equals-method is comparing IDs that are only generated while persisting an object for the first time. They might not be there yet when equals is called.

Related