Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 829
user2148736 Avatar asked Mar 14 '13 21:03

user2148736


People also ask

What will happen if use @service over DAO?

In your scenario, it has no impact on application flow whether you use @Service or @Repository, application will work as they are elligible for autowiring. But standard practice is to use @Repository for dao classes.

Can we use @service in DAO layer?

By convention you can mark DAO classes with @Repository and services with @Service . Also the former does some persistence layer exception translation. Since you are asking theoretically: DAO should perform raw database operations and translate them to some higher level constructs (objects, collections).

What is the difference between DAO and service layer?

Generally the DAO is as light as possible and exists solely to provide a connection to the DB, sometimes abstracted so different DB backends can be used. The service layer is there to provide logic to operate on the data sent to and from the DAO and the client.

What is the use of DAO layer in Spring MVC?

The DAO layer's main goal is to handle the details of the persistence mechanism, while the service layer stands on top of it to handle business requirements.


1 Answers

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.

like image 84
SJuan76 Avatar answered Oct 20 '22 00:10

SJuan76