我应该在JPA实体中编写equals()和hashCode()方法吗? [英] Should I write equals() and hashCode() methods in JPA entities?

查看:174
本文介绍了我应该在JPA实体中编写equals()和hashCode()方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查实体是否在另一个实体的Collection成员(@OneToMany@ManyToMany)中:

I want to check if entity is in a Collection member (@OneToMany or @ManyToMany) of another entity:

if (entity2.getEntities1().contains(entity1)) { }

推荐答案

不一定.共有三个选项:

Not necessarily. There are three options:

  • 请勿覆盖-因此您将使用实例.如果您仅使用连接到会话的实体(因此保证是同一实例)来处理集合,这很好. (对我而言)在许多情况下是首选方式,因为在覆盖时它需要较少的代码和较少的考虑

  • don't override - thus you will be working with instances. This is fine in cases when you are working with the collections with only entities that are attached to the session (and hence guaranteed to be the same instance). This is (for me) the preferred way in many cases, because it requires less code and less consideration when overriding

使用业务密钥覆盖hashCode()equals().那可能是识别实体的属性的子集.例如,对于User,一个好的业务密钥可能是usernameemail.这被认为是很好的做法.

override hashCode() and equals() with a business key. That may be a subset of properties that identify the entity. For example, for a User a good business key might be the username or the email. This is considered good practice.

仅使用ID字段覆盖hashCode()equals().在某些情况下,这很好,特别是在您具有手动分配的标识符(例如UUID)的情况下.如果您的实体永远不会进入集合,也可以.但是对于进入集合的临时实体(没有标识符),这会引起问题,因此请谨慎使用此选项.正如Seanizer指出的-您应该避免使用它.通常,除非您真的知道自己在做什么(也许将其记录在案),否则总是这样

override hashCode() and equals() using the ID field only. This is fine in some cases, especially if you have a manually-assigned identifier (like an UUID). It is also fine if your entity will never go into a collection. But for transient entities (with no identifier) that go into collections, it causes problems, so careful with this option. As seanizer noted - you should avoid it. Generally, always, unless you are really aware of what you are doing (and perhaps documenting it)

请参阅本文以了解更多详细信息.另请注意,equals()hashCode()是绑定的,应在完全相同的字段中实现.

See this article for more details. Also note that equals()and hashCode() are tied and should be implemented both with exactly the same fields.

这篇关于我应该在JPA实体中编写equals()和hashCode()方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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