Should I do caching on DAO layer or service layer in Spring MVC web app?

caching, java, spring-mvc

Solution

First, don't get ahead of things. Before caching, make sure that you need it. Caching can improve performance, but introduces a whole range of headaches (mostly due to losing data coherence).

Second, if you do cache, when possible use third party frameworks like EHCache and the like (yes that is data layer)

Third, in your example, your method signature makes me think that is unlikely that you will get the same request many times. Storing the answer to `getOrderCount(January 27, January 28, String)` will not help you when you get the request for `getOrderCount(March 21, March 28, Vector)`. Unless there is some value that for your bussiness logic is likely to be requested a lot, and calculating the result is heavy enough, the caching (if any) should go into the data layer.

Problem

I would like to cache data in my Spring MVC web application. Because I'm new in Spring Framework and MVC architecture too, I would like to ask if I should cache data (via Spring Caching system) on DAO layer or should I cache ouput methods on a service layer? E.g. I have this method on a service layer: ``` @Override public LinkedList<OrderCount> getOrderCount(Date dateFrom, Date dateTo, Class type) { try { return chartDataDAO.getOrderCount(dateFrom, dateTo, type); } catch (Exception e) { throw new RuntimeException(e); } } ``` and this method calls this DAO method: ``` public LinkedList<OrderCount> getOrderCount(Date dateFrom, Date dateTo, Class type); ``` My question is: should I do caching on service or DAO layer?

Original source