Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My web application is written using Spring MVC + Hibernate.

  • My model is "Customer" entity POJO.
  • I have got a DAO object "CustomerDAO", its method "saveCustomer(c)" contains the code interacting with Hibernate;
  • Then I created a "CustomerService with a "saveCustomer(c)" method who simply pass the customer object to the dao for saving;
  • Finally there are "CustomerController" and customer.jsp, who are responsible for the view layer, the jsp's form fields are bound to a Customer object on the controller side. The controller calls the service.

I saw a lot of applications follow this (best) practice but I'm wondering why I would need a service layer.

Maybe it's useful for decoupling purpose: I can show a universal facade to the controllers and inject into the service HibernateDAO, GaeDAO, MyDAO, and so on.... But I could do that without the service, too: using an interface.

I also tought: validation. I'll make my Customer validation in the service but.... it's much more convenient to validate in Spring controller.

Help me understand the concept please :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
128 views
Welcome To Ask or Share your Answers For Others

1 Answer

You don't need a service layer. However it helps you to

  • Decouple your components
  • You can enforce specific business rules in your service layer which should be agnostic to your repository
  • Let a service facade one or more repositories. Let's consider the following sample
class Service {
  private DatabaseBarRepo barRepo;
  private DatabaseFooRepo fooRepo;

  @Transactional
  public void serviceRoutine() {
     barRepo.doStuff();
     fooRepo.doStuff();
  }
}

Here we let two separate repositories take part in the same transaction. This is specific for databases albeit the principles are valid for other systems as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...