What is DAO and Service layer exactly in Spring framework?
I am looking for theoretical answer.
Generally the DAO layer should be as light as possible and should exist solely to provide a connection to the DB, sometimes abstracted so different DB backends can be used together. The service layer is there to provide logic to operate on the data sent to and from the DAO and the client.
DAO stands for data access object. Usually, the DAO class is responsible for two concepts: encapsulating the details of the persistence layer and providing a CRUD interface for a single entity.
The definition of a DAO is a company that operates without any human involvement. The difference between the two is that a DAO does not have labor while a service has human labor. The difference between DAO and service is that a DAO is an organization without a central manager.
A service layer is a layer in an application that facilitates communication between the controller and the persistence layer. Additionally, business logic is stored in the service layer. It includes validation logic in particular. The model state is used to communicate between the controller and service layers.
There is no distinction as far as Spring is concerned. 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). Services should call DAOs and perform business operations. Typically transactions demarcation is performed on service layer to span several DAO calls.
Finally DAO should abstract business logic from persistence details, ideally allowing to switch persistence layer without business logic (services) changes. This is hardly ever possible due to leaking abstraction of persistence providers (e.g. lazy loading).
DAO - data access object, are object to handle connection to your data storage (typicaly database). You have here your queries and DAO provides data to your services.
Services should contain all your logic. If you have logic separete you can theoretically change your UI layer or DAO layer without you affected it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With