Hibernate object is not cached

In our application, we have configured Hibernate to work with EHcache. The goal is that once the object is loaded into Cache, no db call should be called unless the object has changed.

To test this, I call the object and print identityhashcode

[by calling System.identityHashCode(this)

] the object. And I notice that the identityhashcode

object changes in every call, which makes us feel like the object is being loaded every time.

But we don't see in the logs that Hibernate is making any sql calls to the database.

Can anyone help if my test is correct or not?


source to share

2 answers

There are many things that could explain the difference. Also, not hitting the database can also mean that you are getting objects from the session cache (aka, first level cache). Make sure you create the object in one session and check it out twice in another session (the first one might get into the database, and the second one shouldn't).

It would be ideal to ask Hibernate if the object was fetched from the cache. The easiest way is to enable statistics collection and then print out hits / misses:

Statistics stats = sessionFactory.getStatistics();
... // do your work
long hitCount = stats.getQueryCacheHitCount();
long missCount = stats.getQueryCacheMissCount();




Since you don't see any calls in the database, it's safe enough to say that the cache is working.

The reason you see different hash codes is because EHCache doesn't store objects as they are. Rather, it stores a serialized version that will be deserialized when the cache is hit. From the deserialized version - a new object, therefore different identityHashCode


It's even faster than going to the database.