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?
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.
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
orIdClass
annotation is used to denote a composite primary key.
And when using composite primary keys must follow.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With