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.
Asked
Active
Viewed 179 times
1

Navjot Singh
- 113
- 1
- 9
1 Answers
4
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.

davidxxx
- 125,838
- 23
- 214
- 215
-
I didn't override it on purpose to test. But why is it that different retrievals of same entity will result in a different object. Is it because of some internals of hibernate? Should we ideally override `equals()` and `hashCode()` for each entity we make or some of them could be left out? – Navjot Singh Oct 12 '18 at 19:14
-
Because the default `hashCode()` method inherited from `Object` doesn't produce a hash code value related to the state of the instance but according to some other constraints. So two instances of an entity with same values for each field would not have necessarily (while they may) the same hash code values. That doesn't have any relationship to Hibernate. It is how Java works. – davidxxx Oct 12 '18 at 19:31
-
I got it now. Since when the entity is already in the cache the same memory area is referenced hence same `hashCode`. When loaded in a different persistence context the entity is loaded again and has a different memory location hence different `hashCode` even though the entity is same table row. Also ideally should we override `equals and hashCode` for each entity? – Navjot Singh Oct 12 '18 at 19:39
-
1The overall idea is there but a hashcode is not necessarily memory address of an object. This may interest you : https://stackoverflow.com/questions/16418713/does-hashcode-number-represent-the-memory-address. You want to override `equals()` and `hashCode()` for fair reasons, that is as you notice that you need to do that. So no I would not override these methods systematically. – davidxxx Oct 13 '18 at 11:20