Aubergine Aubergine - 1 month ago 10
Java Question

DAO and Service?

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?

Answer

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.

Comments