Reputation: 1012
In my web application (Spring 3.1, Hibernate 4), I am using Ehcache for Hibernate 2nd level cache and Spring @Cache. I would like to know, where to use Hibernate Cache and Spring Cache?
For Example, I have few domain classes (view in database) which I am using as lookup values on screen. I can cache them using Hibernate 2nd level cache as well as Spring @Cache.
So, in my service layer if I cache these domain objects using Spring @Cache, I would receive these objects without hitting persistence layer at all (hibernate HQL query), once cached. Is it right approach?
Upvotes: 1
Views: 1987
Reputation: 128909
The right approach is:
The moral of the story is that you don't cache because it's cool. You cache for performance. And you only optimize code when it's proven necessary.
Upvotes: 0
Reputation: 23565
Depends on your layer architecture.
Assume you have three services (or three methods within the same service) that all return a collection of Customer
entities i.e. domain objects. If you cache at service layer there's a fair chance the same representation of a single database record will live in the cache multiple times. They are multiple objects of essentially the same information. Why? Because the results of Service.getWhateverCustomers(String)
and Service.getWhateverCustomers(String, Integer)
are stored under two different cache keys.
If you cache at entity level using the JPA @Cachable annotation on the other hand your Customer
entity is cached no matter from which service or service method you call the code that actually retrieves the entity. Of course the rules about when the JPA provider can/does cache an entity apply. Read up on them if you're not familiar with them.
Hope this gives you an idea which path to follow. Post follow-up comments if you have more questions and I'll edit this answer.
Upvotes: 4