Should I write equals() and hashCode() methods in JPA entities?

Not necessarily. There are three options:

  • don’t override – thus you will be working with instances. This is fine in cases when you are working with the collections with only entities that are attached to the session (and hence guaranteed to be the same instance). This is (for me) the preferred way in many cases, because it requires less code and less consideration when overriding

  • override hashCode() and equals() with a business key. That may be a subset of properties that identify the entity. For example, for a User a good business key might be the username or the email. This is considered good practice.

  • override hashCode() and equals() using the ID field only. This is fine in some cases, especially if you have a manually-assigned identifier (like an UUID). It is also fine if your entity will never go into a collection. But for transient entities (with no identifier) that go into collections, it causes problems, so careful with this option. As seanizer noted – you should avoid it. Generally, always, unless you are really aware of what you are doing (and perhaps documenting it)

See this article for more details. Also note that equals()and hashCode() are tied and should be implemented both with exactly the same fields.

Leave a Comment