为了等于和哈希码或不在实体类,这是问题 [英] To equals and hashcode or not on entity classes, that is the question

查看:98
本文介绍了为了等于和哈希码或不在实体类,这是问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图推断处理在实体上实现哈希码和等于一般情况的良好做法的最佳方法(我的意思是实体在一般意义上,但在大多数情况下,它将是一个JPA实体) p>

在Hibernate手册的第24章 http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html 它说这... ...


确定所有
实体的自然键,并使用
映射它们。实现equals()和
hashCode()来比较组成自然键的属性

.equals和.hashcode只包含这些自然键是有意义的,但是如果你有多个同一实体的实例(相同的自然ID,因此相同的散列码)呢?看起来这种做法可能会在你的应用程序的其他地方产生微妙的影响。有人曾经大规模地尝试过这个吗?

解决方案

有时您希望Equals比较所有属性和时间,当您希望Equals只是关键时。我们已经使用很明显的帮助类获得了更多的成功,所以在比较什么时候没有歧义。

  ByKeyComparer.Equals ... 
ByPropertiesComparer.Equals ...

  Entity1.EqualsByKey ... 
Entity1.EqualsByProperties ...


I have been trying to reason about the best way to handle whether it is generally good practice to implement hashcode and equals on entities (I mean entity in the general sense but in most cases it will be a JPA entity).

In Chapter 24 of the Hibernate manual http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html it says this...

Identify natural keys for all entities, and map them using . Implement equals() and hashCode() to compare the properties that make up the natural key.

It makes sense to have .equals and .hashcode include only these natural keys but what if you have more than one instance of the same entity (same natural id thus same hashcode)? It seems like this practice could have subtle implications elsewhere in your application. Has anybody tried this before on a large scale?

解决方案

There are times when you want Equals to compare all properties and times when you want Equals to be just the key. We've had a lot more success using helper classes that are explicit so there isn't ambiguity as to what's being compared.

ByKeyComparer.Equals...
ByPropertiesComparer.Equals...

or

Entity1.EqualsByKey...
Entity1.EqualsByProperties...

这篇关于为了等于和哈希码或不在实体类,这是问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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