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

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

问题描述

我想检查实体是否在另一个实体的集合成员(@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天全站免登陆