Ketan
Ketan

Reputation: 1012

Caching (Ehcache) - Hibernate 2nd level cache and Spring

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

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128909

The right approach is:

  1. Ask yourself if you even need to mess with the complexity of caching. Is your app failing to perform up to requirements?
  2. Only if the answer to the previous question is "yes", profile your app to find out where the performance problem(s) is/are.
  3. Determine the appropriate way to solve a performance problem identified in step 2. It may or may not involve caching to prevent costly operations. If it does involve caching, then where to cache and which cache to use should be abundantly clear because you'll know exactly what you're trying to prevent from happening.

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

Marcel Stör
Marcel Stör

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

Related Questions