Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA/Hibernate "Composite-id class does not override equals()"

Tags:

java

jpa

I'm using JPA and getting the following warning. I've researched this, and understand why I need to override it and how Hibernate uses these methods. I still have a question though:

Exception:

Composite-id class does not override equals()

Question:

Why does Hibernate only care about classes that don't have composite IDs? Does it by default compare on the @Id field if there is only one present, or is there something more complex going on here?

like image 407
John Humphreys Avatar asked Mar 25 '14 21:03

John Humphreys


2 Answers

Because when entities don't have a composite ID, they have a single one, of one of the basic supported types (Integer, Long, String, etc.), and those classes already have a well-defined equals() (and hashCode()) method.

like image 136
JB Nizet Avatar answered Oct 17 '22 16:10

JB Nizet


Using JPA when you use composite key, you should use either IdClass or EmbeddedId using any of them you need to create an own class that act as a composite key, in order to be able to compare objects using this composite key which is required by several operations within the EntityManager that key classes must to override equals and hashCode.

Taking from specs:

A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId or IdClass annotation is used to denote a composite primary key.

And when using composite primary keys must follow.

  1. The primary key class must be public and must have a public no-arg constructor.
  2. The primary key class must be serializable.
  3. The primary key class must define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
like image 8
Koitoer Avatar answered Oct 17 '22 15:10

Koitoer