Loosing control from my hands

I am a strong beliver of "If u want to do it correct, do it yourself", and yes I applied it successfully till now. I like doing things with vanila JDBC, because I feel having control in my hand, but Hibernate I used just for simple ORM where my mappings were very simple.


This post is not about Hibernate mapping and complexity but it is about caching in hibernate so I will come direct to the point.


My requirement was quite simple. I just wanted to do caching of objects retrived from DAO. I thought of using Hibernate caching. My idea was very simple that I will use second level caching and no work in any layer.


First it was very difficult to enable it, found only a few blogs on it which were also not complete. I defined all the hibernate caching properties. I tried to use EhCache but could not, because dependecies issues and its configuration without any proper documentation. Anyways I used OSCache and it was simple to use, just set the provider class and enable second level caching.


WYTYDG (What You Think You Don't Get), yes this is what happened. I thought I will get same instance from cache again and again but it was not like that. When second level cache is disabled it queries database for each load operation, this is perfect, when second level cache is enabled it does not query database, that is also perfect but what you get from load is a completely different object. It does not return the same object reference from cache. It gives a copy of cached object, means memory gets the same load of objects you just save the database trip.


At the end I had to implement one more layer of caching on my DAO, which worked as I expected. Anyways the point is if you just want to save database trip, use hibernate second level cache, if you want to get same object use your own caching (which can use any other caching mechanism like EhCache or OSCache).

Comments