views:

22

answers:

1

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 to true in your configuration
  • choose a 2nd level cache provider (I suggest EHCache)
    • set the hibernate.cache.provider_class property accordingly
  • mark your entities as cacheable (using the read-only strategy)
    • Add @Cache(usage = CacheConcurrencyStrategy.READ_ONLY) to your entities

References

More Resources

Pascal Thivent
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
@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