正确实施JPA实体的equals()方法 [英] Correct way of Implementation of equals() method for JPA entities

查看:188
本文介绍了正确实施JPA实体的equals()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Eclipse为我的JPA实体生成 hashcode() equals()方法,方法是选择字段/ b>

但是,我发现Eclipse似乎在生成的 equals 方法中添加了下面的行:

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

具有上述检查似乎符合逻辑,但我在所有JPA实体中使用LAZY加载的关系,并且我发现在某些情况下,当 obj 的类是某种代理类并且主要对象是所讨论的实体时,上面的检查失败 - 我检查过被比较的对象类和两个不完全相同,因此即使对象表示数据库中的相同记录,上述条件的计算结果为 false



因此,当我们为JPA实体实现 equals()方法时,我的查询应该比较对象的类别。

解决方案

建议对JPA实体使用业务键相等
自动生成的等于使用所有字段。

很可能您的实体拥有技术性自动生成的主键(id字段)。在实体被保存后,该字段由数据库填充。
如果您有自动生成的equals / hashcode,它将包含所有类字段 - 包括该id字段。
因此,在您保留实体后,您的实体的等号/哈希码将会更改,而不会更改任何其他字段(在persist id保留为空之后,保留为空之后)。

欲了解更多详情,请阅读
https://docs.jboss.org/hibernate/stable/core.old/reference/en/html/persistent-classes-equalshashcode.html



这是Hibernate引用,但与主键相关的所有概念都应该适用于任何JPA提供者。


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.

这篇关于正确实施JPA实体的equals()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆