3

In our application we have configured Hibernate to work with EHcache. Aim is that once object is loaded in Cache, no db call should every be invoked unless object is changed.

In order to test this, i am making call to object and printing identityhashcode [using call System.identityHashCode(this)] of object. And i notice that identityhashcode of object is changing in every call which makes us feel that object is loading everytime.

But in logs, we donot see Hibernate making any sql calls to database.

Can someone please guide, if my test is correct or not?

Lokesh
  • 7,810
  • 6
  • 48
  • 78

2 Answers2

3

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

The reason you see different identity hashcodes is because EHCache doesn't store the objects as is. Rather it stores a serialized version, which it will deserialize when there's a cache hit. The deserialized version is a new object, hence the different identityHashCode.

It's still faster than going to the database.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
3

There are many things that might explain the difference. Also, not hitting the database might 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 retrieve it twice in another session (the first might hit the database, the second shouldn't).

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

Statistics stats = sessionFactory.getStatistics();
stats.setStatisticsEnabled(true);
... // do your work
long hitCount = stats.getQueryCacheHitCount();
long missCount = stats.getQueryCacheMissCount();
jpkroehling
  • 13,881
  • 1
  • 37
  • 39