简体   繁体   English

JPA实体实现equals()方法的正确方法

[英]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. 我已经使用Eclipse通过选择感兴趣的字段/属性来为我的JPA实体生成hashcode()equals()方法。

However, I have observed that Eclipse seems to add below lines in generated equals method: 但是,我发现Eclipse似乎在生成的equals方法中添加了以下几行:

    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. 进行上述检查似乎合乎逻辑,但是我在所有JPA实体中都使用LAZY加载的关系,并且我观察到在某些情况下,当obj的类是某种代理类并且主对象是obj的类时,上述检查失败有问题的实体-我检查了要比较的对象的类,并且两者并不完全相同,因此,即使对象表示数据库中的相同记录,上述条件的评估结果也是false

Hence, my query is should we compare class of objects when we implement equals() method for JPA entities. 因此,我的查询是在为JPA实体实现equals()方法时是否应该比较对象的类。

It is recommended to use business key equality for JPA entities. 建议对JPA实体使用业务密钥相等性 Autogenerated equals uses all fields. 自动生成的等于使用所有字段。

Most likely your entity has technical, autogenerated primary key (id field). 您的实体很可能具有自动生成的技术主键(id字段)。 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. 如果您具有自动生成的equals / hashcode,它将包括所有类字段,包括该id字段。 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). 因此,您的实体的equals / hashcode将在您将其持久化后更改,而不会更改任何其他字段(持久化ID之前为null,持久化之后不为null)。

For more details read https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html 有关更多详细信息,请阅读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. 这是Hibernate参考,但是与主键有关的所有概念都应适用于任何JPA提供程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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