Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DAO and Service?

Tags:

java

spring

dao

I'm always facing a problem where I can't really think of service object encapsulating many DAO methods.

I mean that for my servlet sometimes it is sufficient to use single DAO method, for example addUser(User params).

What is better to do - to encapsulate DAO methods with service object and use only service objects ALWAYS, even if it literally means a single service method calling single dao method or mixing their use together(some methods from service objects and some from dao in servlet context) - meaning that I have autowired DAOs and Service objects inside controller ?

It mixes up the logic if I start to use both DAO and Service object in the same place?

like image 306
Aubergine Avatar asked Nov 25 '11 19:11

Aubergine


People also ask

What is difference between DAO and service?

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.

Can you use @service over a 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.

What is Controller Service DAO?

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.


1 Answers

I think this depends on the situation. If not having a DAO is going to cause mixing your business logic and your data access logic, it is probably better to have separate classes.

However, if your DAO is "dummy" and just calls an EntityManager method, you can probably use this directly in your service objects. The idea is to have classes that have single responsibilities and are easy to extend and test. You shouldn't be creating layers for the sake of it.

I probably wouldn't use DAOs directly from your controllers if you want to keep a reusable service layer. I would rather use the EntityManager (or whatever persistence strategy you are using) in the service layer if the DAO doesn't make sense.

like image 93
Gonzalo Garcia Lasurtegui Avatar answered Sep 28 '22 06:09

Gonzalo Garcia Lasurtegui