简体   繁体   中英

Correct way of Implementation of equals() method for JPA entities

I have used Eclipse to generate hashcode() and equals() methods for my JPA entities by selecting fields/attributes of interest.

However, I have observed that Eclipse seems to add below lines in generated equals method:

    if (getClass() != obj.getClass())
        return false;

It seems logical to have the above check, but I am using LAZY loaded relations in all my JPA entities, and I have observed that in certain instances above check fails when obj 's class is some kind of proxied class and the main object is of the Entity in question - I have inspected the class of objects being compared and both are not exactly same, and hence the above condition evaluates to false even though the objects represented same record from database.

Hence, my query is should we compare class of objects when we implement equals() method for JPA entities.

It is recommended to use business key equality for JPA entities. Autogenerated equals uses all fields.

Most likely your entity has technical, autogenerated primary key (id field). That field is populated by database, after entity is persisted. If you have autogenerated equals/hashcode, it includes all class fields- including that id field. Therefore equals/hashcode for your entity will change after you persist it, without changing any other field (before persist id will be null, after persist not null).

For more details read https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html

this is Hibernate reference, but all concepts related to primary key should apply to any JPA provider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM