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

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

问题描述

我想检查实体是否在另一个实体的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)) { }


推荐答案

不一定。有三个选项:


  • 不要覆盖 - 因此您将使用实例。当您使用仅附加到会话的实体(因此保证是相同的实例)处理集合时,这很好。在许多情况下,这是(对我而言)首选方式,因为它需要更少的代码,并且在覆盖时需要更少的考虑

  • 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( )等于()带有业务键。这可能是标识实体的属性的子集。例如,对于用户,一个好的商业密钥可能是用户名电子邮件。这被认为是一种很好的做法。

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.

覆盖 hashCode()等于( )仅使用ID字段。在某些情况下这很好,特别是如果您有一个手动分配的标识符(如UUID)。如果您的实体永远不会进入集合,那也没关系。但对于进入集合的瞬态实体(没有标识符),它会导致问题,因此请谨慎使用此选项。正如海员所说 - 你应该避免它。一般来说,除非你真的知道你在做什么(并且可能记录下来),否则

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()方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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