Service Layer vs DAO in Java – Why Both Are Needed

hibernatejavaspring-mvcweb-applications

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/

Best Answer

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.