Service layer vs DAO -- Why both?
I have been working with SpringMVC, Hibernate, and some databases in a java web application example.
There are a few different ones that do this, but this Spring 3 and hibernate integration tutorial with example has a model class, view (in jsp), and a service and dao classes for the controller.
My question is, don't both the service and DAO classes do the same thing? Why would you need them both?
This was the tutorial I was actually using: http://fruzenshtein.com/spring-mvc-security-mysql-hibernate/
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. Very often these 2 pieces will be bundled together into the same module, and occasionally into the same code, but you'll still see them as distinct logical entities.
Another reason is security - If you provide a service layer that has no relation to the DB, then is it more difficult to gain access to the DB from the client except through the service. If the DB cannot be accessed directly from the client (and there is no trivial DAO module acting as the service) then all an attacker who has taken over the client can do is attempt to hack the service layer as well before he gets all but the most sanitised access to your data.
I agree with the separation of service and dao layers and your service layer containing your business logic.
not to mention that 1 service might call several DAOs, for example when saving an user you might talk to the UserDao, the UserOrdersDao, etc Or should we create one service for each? And then who could call all of these services?