пятница, 5 марта 2010 г.

Second level cache in hibernate

Do you use hibernate ? I guess - yes, if you are here.
Do you use second level cache and query cache with hibernate? Are you happy with performance? I dont know... probably. Actually I am not happy with hibernate performance with query cache and 2nd level cache. Lets look inside ;)
First of all you have to understand, that 2nd level cache used when you perform lookup entity by id. Sound good, but by default entity will be cache without collections. The first solution - enable cache for collection in configurations, it will works for bags, lists, collections, sets, maps.
Second - query cache. It cache only the ids and must be used in conjunction second level cache.
Everything not bad at surface, but when you create hibernate and ehcache configuration and run you solution you will be surprised. Hibernate still hit you db :( Root cause - collection cache will not works for map, that has a map-key, and you db will be hitted a lot of times per single entity.
How to solve this ? Throw away the hibernate cache and use cache aspect in your application, it save a lot of you times, IO operations and CPU. It more predictable way that hibernate cache and allow to cache that you really need :)