2

Hi Guys I am new to Spring.Just had a doubt .The service and DAO classes do the same thing? Why would you need them both? Apart from that we can connect our controller directly to our Dao methods and we can fetch data from them. Whats the need for SERVICE Layer exactly. I went through few portals some of whom told service layer provides modularity and few of them mentioned that its for security purpose also. I am still confused Can anyone provide a clear cut answer for this query?

1
  • Every concern which does not do SQL explicilty -- security, input validation, logging, "business logic" above all -- must go into service layer. Jul 5, 2014 at 9:28

3 Answers 3

3

Service layer is necessary in case of transaction and rollback case . assume one case that you have one method which perform multiple update or delete.in such case your controller might not support transaction but in service layer spring provides you way to commit and rollback

Having the service layer be a wrapper around the DAO is a common anti-pattern. In the example you give it is certainly not very useful. Using a service layer means you get several benefits:

you get to make a clear distinction between web type activity best done in the controller and generic business logic that is not web-related. You can test service-related business logic separately from controller logic.

  • you get to specify transaction behavior so if you have calls to multiple data access objects
  • you can specify that they occur within the same transaction
  • you can nest services so that if one has different transactional behavior (requires its own transaction) you can enforce that.
  • you can use the postCommit interceptor to do notification stuff like sending emails, so that doesn't junk up the controller.

Typically I have services that encompass use cases for a single type of user, each method on the service is a single action (work to be done in a single request-response cycle) that that user would be performing, and unlike your example there is typically more than a simple data access object call going on in there.

3

Purpose of service layer is to use DAO(s) to implement your business logic. I have enlisetd few benifits of Service layer below

  • Service layer can use transactions to perform atomic operations.Using Transaction in DAO layer does not make sens(for complex use case) as there can be multiple entity involved in the operation.

  • With help of Service Layer we can extend Session scope to request instead of Session per operation.

  • Service Layer can be used to handle business specific Exception and can throw new business exception that can be used to display Error Page. Throwing Business specific exceptions like BadCredentials or InvalidInput from DAO adds extra responsibility to DAO to validate username and password. Ideally DAO is just for communication with Database and all the business logic should be in Service layer.

  • One service can use multiple Services to perform workflow and allows code re-usability.

e.g. Use case

This is Simple Implementation of DAO which may fail during when there is concurrent access to same database row. Suppose there are two operations A and B. Operations Aand B want to create user with same username if its not already there.

Operation A starts -- > getUser("abc") returns null ---> hence createUser(abc).

Operation B starts ---> getUser("abc") return null as transaction A has not created yet user abc---> hence createUser(abc), this will throw either Database exception for duplicate primary key if we use username as primary key or we can have two users with same username if we use surrogate key as Operation A has created user abc in earlier transaction.

public class UserDao{


public User getUser(String Username){

    User user = null;
    Session session = SessionFactory.OpenSession();
    Transaction tx = session.beginTransaction();

    // Some logic here...//
    tx.commit();
    session.close();
    retur user;
}

public User createUser(User user){

    Session session = SessionFactory.OpenSession();
    Transaction tx = session.beginTransaction();
    // Some logic here...//
    tx.commit();
    session.close();
}

}


public class NewUserDao{


public User getUser(String Username){

    User user = null;
    Session session = SessionFactory.getCurrentSession();
    // Some logic here...//
    return user;
}

public User createUser(User user){

    Session session = SessionFactory.getCurrentSession();
    // Some logic here...//
    return user;
}

}

public class UserService{

New UserDao newUserDao; //Dependecy injection

@Transactional
public User createUser(User user){

if(newUserDao.getUser(user.getUserName())== null){
    newUserDao.createUser(user);
}

}

}
2

You should put in the DAO all the access to database and you shouldn't put business logic here. All logic should go in the services, and the services should call the DAOs to make queries to database.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.