DAO and Service? DAO and Service? spring spring

DAO and Service?


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.


I am working with a system where the "you cannot have the controllers interact with the DAOs!" design philosophy was embraced at a point and a service layer was created for every component. Most of the services are, as you describe, simply delegating to a DAO. I object to this philosophy for two reasons.

One is the good old "You aren't gonna need it". Don't implement something until you need it. Just because you foresee some reason to have an extra layer of indirection to do some extra logic, it's not sure you're going to need it. And when you end up needing it, you will probably find out that your expectations didn't really match what you believed earlier. And you get an extra cost, because now you have to unit test two classes instead of one, and it's not uncommon that you need to add methods in two places instead of one.

The second is, what the heck is a service anyway? When I model my domain, I try to think in object-oriented terms. There are users, therefore the User class makes sense. There are news items, therefore the NewsItem class makes sense. But I don't even know what a UserService is supposed to do. Contain "business logic" for users? No, that's what the User class is there for.

If you need to maintain a strict API to the "outside world", then I can see a case to have an extra layer that remains unchanged. But in all other cases, you aren't going to need it.


Personally, I usually encapsulate DAO calls within services.

This allows me to make all services transactional using AOP/etc. and use non-transactional DAO methods within those services.

For trivial services, this is an additional "layer", but IMO one that serves a purpose (and code generation of one sort or another can be used to generate it anyway). It's also rare I have only DAO functionality wrapped up in a service, though.