Responsibilities and use of Service and DAO Layers

55,636

Solution 1

It is a good idea to have those two layers when your business logic is more complex than your data logic. The service layer implements the business logic. In most cases, this layer has to perform more operations than just calling a method from a DAO object. And if you're thinking of making your application bigger, this is probably the best solution.

Imagine you want to include a City entity and create a relationship between People and City. Here is an example:

@Transactional
public class PeopleService {

    ....
    private PeopleDAO pDAO;
    private CityDAO cDAO;

    ...

    public void createPerson(String name, String city)
     throws PeopleServiceException {
        Person p = new Person();
        p.setName(name);

        City c = cDAO.getCityByName(city);
        if (c == null) throw new ServiceException(city + " doesn't exist!");
        if (c.isFull()) throw new ServiceException(city + " is full!");
        c.addPeople(p);

        sess().save(p);
        sess().save(c);
    }

    ...
}

In this example, you can implement more complex validations, like checking the consistency of the data. And PersonDAO has not been modified.

Another example:

DAO and Service layers with Spring

Definition of Service layer pattern

Solution 2

If your application will grow with new and changing requirements you are very well served with having distinct layers for those TWO DISTINCT ASPECTS (persistence->DAO, business use case -> services) of your software.

One aspect is your persistence model with its relations, validations, transactions and many access patterns.

The services are driven by the business use cases which have a very different granularity. In the beginning you may have very simple services which don't do much more than calling DAOs to hand over data they received from, let's say, a web page. But this is likely to change over time and services will grow into small networks of collaborating objects that do a lot more to serve the business use case. If you don't use DAOs then

  • your services will contain code that deals with querying objects, transaction handling, validation, all of which has nothing to do with real business requirements
  • service code will look messy and it will be difficult to find out what parts of the code are actually business related
  • if you then change the persistence model you might end up changing many services

Also you can not easily unit test your persistence model but write tests only on the service layer. Do not forget that decoupling and encapsulation are important techniques to minimize the impact of change.

When done right, having a DAO layer will not introduce much implementation overhead so there is not much extra cost in having it. It will soon pay off and you will be very glad to have this dedicated layer.

Check out this article: http://codeblock.engio.net/?p=180. It also comes with a full implementation hosted on github

Share:
55,636
user962206
Author by

user962206

Updated on March 04, 2020

Comments

  • user962206
    user962206 over 4 years

    I am currently developing a web application using Struts2 with Spring plugin and hibernate and while I was looking at online examples I saw the use of Service and DAO layers now it came to me what are the real use of Service and data access object layers? If The Service layer is just calling the methods of DAO layers to perform CRUD operations. wouldn't be sensible to just call the DAO layers methods directly?

    Let's say this example of Dao and Service Layer

    PeopleService

      @Transactional
        public class PeopleService {
    
            private PeopleDao pDao;
    
            public PeopleDao getPDao() { return pDao; }
    
            public void setPDao(PeopleDao peopleDao) { this.pDao = peopleDao;   }
    
            public void createPerson(String name){
                pDao.createPerson(name);
            }
    
            public List<Person> getPeople(){
                return pDao.getPeople();
            }
    
        }
    

    PeopleDao

    public class PeopleDao {
    
        private SessionFactory sessionFactory;
    
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
    
        public Session sess() {
            return sessionFactory.getCurrentSession();
        }
    
        public Person getPersonById(long id) {
            return (Person) sess().load(Person.class, id);
        }
    
        public void deletePersonById(long id) {
            sess().delete(getPersonById(id));
        }
    
        public void createPerson(String name) {
            Person p = new Person();
            p.setName(name);
            sess().save(p);
        }
    
        @SuppressWarnings("unchecked")
        public List<Person> getPeople() {
            return sess().createQuery("from Person").list();
        }
    
    }
    

    My question is what is the real use of Service layers if they are only being injected by their representative DAO and then calling its method?

  • user962206
    user962206 over 11 years
    Isn't the POJO implments the bussiness logic and other validations? (while validations can be done on client side)
  • CarlosMecha
    CarlosMecha over 11 years
    You mean the entity Person? Not always. A simple validation, it could be done by Person (name not null, or name size > 50), but if other entities have relationships with Person, it will be difficult to maintain. Also, if you don't control the client side (example, public APIs), you have to validate at Service layer.
  • Tom Anderson
    Tom Anderson over 11 years
    I note your PeopleService doesn't actually use the PeopleDAO, it uses the session directly. I think that very well illustrates the point that, in cases like this, the DAO is not really necessary!
  • CarlosMecha
    CarlosMecha over 11 years
    Well, this is not a big example. You will probably have a method that uses one or more DAOs (e.g. moveToOtherCity(person, city)). Of course there are some cases that Service and DAO layers are the same. The point is, in general, is a good design separate those layers, so you can modify your business logic, but not your data access.
  • user962206
    user962206 over 11 years
    Wait let me get this Straight, so my business logic will be placed inside the Service Layer not the POJOS? I thought that POJOs should always contain the Business logic?
  • CarlosMecha
    CarlosMecha over 11 years
    When you say POJO I suppose you're referring to the Person class, right? Or DAOs? (Not always a POJO is just an data entity). The Person class is a Business (or Domain) object, and the Service layer implements Business (or Domain) logic. The DAOs usually implements just the CRUD actions in business objects.
  • user962206
    user962206 over 11 years
    Yes you are right, I mean the Person class. When you say Business logic do you mean logical computations and such? Let's say I have an app that performs complex computation from the data it received, will my Domain object do the computation or the Service Layer?
  • CarlosMecha
    CarlosMecha over 11 years
    In that case, if the complex operation is a service (users can request it), it should be placed in the Service layer, taking data from different business objects (if is needed) and input information. I might be wrong, but a good thumb rule is: If the operation needs external data (from other domain objects, input information, etc) is better to place it in a upper layer. Otherwise, the domain object could contain it.
  • user962206
    user962206 over 11 years
    I see because what I have in mind is that the Domain objects will be coordinated with each other to perform complex task or computation(or data conversion) inside the service layer therefore the service layer will still have the business logic and at the same time the Domain object will still have its logic. The Service Layer is just coordinating it or am I wrong?
  • CarlosMecha
    CarlosMecha over 11 years
    Exactly, both sides have business logic. Service layer will coordinate domain objects, so its business logic is more complex. And domain objects are just aware of their own business (or domain) logic.
  • user962206
    user962206 over 11 years
    Although you have explained it wll can you provide links to other examples? I get it I just want to see a concrete example
  • inigoD
    inigoD almost 5 years
    Old question and old response, but I have to say it (and don't take it wrong); your first paragraph is the definition of YAGNI. Could it be that, in the case of @user962206, they don't need it and so they should not create that service layer?
  • Stu_Dent
    Stu_Dent over 3 years
    What about working with Servlet? how servlet handle this method? just call save Person method?