java - 在 Hibernate 中存储在 Set 中时的 equals() 和 hashCode()

标签 java hibernate jpa

在第 4.3 章的 Hibernate 文档中。 “Implementing equals() and hashCode()”他们写了这句话:

"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."

我不明白它违反了什么契约以及它会带来什么问题。

最佳答案

HashSet(由 HashMap 支持)在对象的哈希码不变时起作用。那是因为它根据哈希码保存它们。

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

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

同时检查 this question对于 hashCode()equals(..)

你有什么选择

关于java - 在 Hibernate 中存储在 Set 中时的 equals() 和 hashCode(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5847272/

相关文章:

mysql - Hibernate 在 MySQL 上发出太多查询

java - 将 SQL 左外连接查询转换为 JPA 条件

java - JCEKS keystore 不再加载 : com. sun.crypto.provider.SealedObjectForKeyProtector

java - 如何将 WebStart JNLP 与 JRE 捆绑在一起

java - 绘制扩展 JPanel 的类

java - 是否可以将 Java 1.5 源 Web 应用程序编译为 1.4?

hibernate - 使用 Hibernate 删除一对多关系中的对象时出现 PostgreSQL 异常

java - Nullable @ManyToOne 不接受 null 值

java - 错误: column is of type bit but expression is of type boolean

java - 没有名为 testPU 的 EntityManager 的持久性提供程序