Search code examples
javahibernateormpersistence

Different hashCode() in different persistence context?


I open two different sessions in Hibernate each running their own transaction. Each session retrieves the same entity from the table. When i print their hashCode() they are different. Why does this happen? If we retrieve the same entity in the same session then the hashCode() is same. What is the reason behind this.


Solution

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

    It is expected as the first level cache of Hibernate (the Session here) keeps the entities loaded inside the transaction in cache for the transaction lifespan.
    The entity is not retrieved a second time, it is just retrieved from the cache.

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

    As loaded entities are not shared between sessions, it means that you didn't override hashCode() for the entity.
    So to guarantee the same hashCode() and also their equality (equals()), override equals()/hashCode() if it makes sense.