I have few tables like Country,state city which has static data. User do not enter any data in this data. I create pojo for Country, State, City. There are few pojo which has mapping with static data. My requirement is that whenever any request comes to Hibernate for Country (21), it do not hit database but return data from cache . Is this possible in Hibernate. I need few pointers and your views to implement caching in my project. I am using hibernate annotations.
+5
A:
My requirement is that whenever any request comes to Hibernate for Country (21), it do not hit database but return data from cache. Is this possible in Hibernate.
Yes, this is possible using the Second Level Cache and this kind of Entities (read-only) are the perfect candidates for caching (they are the easiest to manage). You'll need to:
- enable the 2nd level cache
- set the
hibernate.cache.use_second_level_cache
property totrue
in your configuration
- set the
- choose a 2nd level cache provider (I suggest EHCache)
- set the
hibernate.cache.provider_class
property accordingly
- set the
- mark your entities as cacheable (using the
read-only
strategy)- Add
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
to your entities
- Add
References
- Hibernate Core Reference Guide
- Hibernate Annotations 3.4 Reference Guide
More Resources
Pascal Thivent
2010-10-07 10:50:08
When i run query select * from country where countryname like '%somename%' i can see the query in my console. I enable query cache but somehow it is not working. Can i force hibernate to get all cacheable data on startup and do not talk to database further more.
dmay
2010-10-11 14:14:28
@dmay I'm not sure the L2/query cache works with like queries. But to answer your questions, the features provided by Hibernate are described in my answer.
Pascal Thivent
2010-10-11 14:22:13