在Hibernate中存储在Set中时,equals()和hashCode() [英] equals() and hashCode() when storing in a Set, in Hibernate

查看:105
本文介绍了在Hibernate中存储在Set中时,equals()和hashCode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Hibernate文档的第4.3章中. "实现equals()和hashCode( )",他们写下了这句话:

In Hibernate documentation in chapter 4.3. "Implementing equals() and hashCode()" they wrote this sentence:

此外,如果实例尚未保存并且当前在Set中,则保存该实例将为该对象分配一个标识符值.如果 equals() hashCode()基于标识符值,哈希码将发生变化,从而破坏Set的合同."

"Furthermore, if an instance is unsaved and currently in a Set, saving it will assign an identifier value to the object. If equals() and hashCode() are based on the identifier value, the hash code would change, breaking the contract of the Set."

我不知道它会打破什么合同,以及由此会带来什么问题.

I don't understand what contract it breaks and what problems can arrive from it.

推荐答案

a HashSet(由HashMap支持)在对象的哈希码未更改的情况下有效.那是因为它根据它们的哈希码保存它们.

a HashSet (backed by HashMap) works if the hashcodes of objects do not change. That's because it holds them based on their hashcodes.

因此,如果您将hashCode()基于标识符,并将没有标识符的实体放在一起,则它们都将具有相同的哈希码.如果它们也是equal(..)(将是),则它们将不允许集合中有多个对象.

Thus, if you base your hashCode() on the identifier, and put entities without identifier, they will all have the same hash code. Which, if they are also equal(..) (which they will be), will not allow more than one object in the set.

现在,如果集合中有一些具有分配的标识符的实体,而没有标识符的实体随后被保存,则该集合将具有错误的哈希码.

Now, if the set has some entities with assigned identifier and one without, which is later saved, then the set will have the wrong hashcode for it.

还要检查这个问题是什么您关于hashCode()equals(..)

Also check this question for what are your options about hashCode() and equals(..)

这篇关于在Hibernate中存储在Set中时,equals()和hashCode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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