不同持久化上下文中的不同 hashCode()?

Different hashCode() in different persistence context?

我在 Hibernate 中打开两个不同的会话,每个会话 运行 它们自己的事务。每个会话从 table 检索相同的实体。当我打印他们的 hashCode() 时,他们是不同的。为什么会这样?如果我们在同一个会话中检索同一个实体,那么 hashCode() 是相同的。这背后的原因是什么。

If we retrieve the same entity in the same session then the hashCode() is same.

预计 Hibernate 的一级缓存(此处 Session)会在事务生命周期内将事务中加载的实体保存在缓存中。
该实体不会被第二次检索,它只是从缓存中检索。

Each session retrieves the same entity from the table. When i print their hashCode() they are different.

由于加载的实体不会在会话之间共享,这意味着您没有为实体覆盖 hashCode()
因此,为了保证相同的 hashCode() 以及它们的相等性 (equals()),如果有意义,请覆盖 equals()/hashCode()