我一直在试图推理处理在实体上实现哈希码和等于是否通常是好的做法的最佳方法(我的意思是一般意义上的实体,但在大多数情况下它将是 JPA 实体)。
在 Hibernate 手册的第 24 章 http://docs.jboss.org/hibernate/core/3.3/reference/en/html/best-practices.html它说这个...
Identify natural keys for all entities, and map them using . Implement equals() and hashCode() to compare the properties that make up the natural key.
让 .equals 和 .hashcode 只包含这些自然键是有意义的,但是如果您有多个相同实体的实例(相同的自然 id 因此相同的哈希码)怎么办?似乎这种做法可能会对您应用程序的其他地方产生微妙的影响。以前有人大规模尝试过吗?
最佳答案
我之前已经大规模尝试过这个(或者至少在一个大量使用 hibernate 的应用程序中)。是个好主意。
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.
这就是它的意义所在。您通常 想要比较 .equals 时,同一实体的多个实例会成功,是的,它对其他地方有影响。 IMO 这些含义是事情会按预期进行。
关于hibernate - 在实体类上是否等于和哈希码,这就是问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1929445/