Do I really need a service layer?

后端 未结 5 1134
执念已碎
执念已碎 2020-12-08 07:51

My web application is written using Spring MVC + Hibernate.

  • My model is \"Customer\" entity POJO.
  • I have got a DAO object \"CustomerDAO\", its method
相关标签:
5条回答
  • 2020-12-08 08:06

    There are other things that you at service layer. Sometime its about applying business rules before passing any action to DAO. Sometimes one service needs to interact with other services, DAO for the business rules requirement.

    Tell us how you'll do without server layer and with an interface..high level idea, will help me to tell you more.

    0 讨论(0)
  • 2020-12-08 08:09

    You can save the verbosity by having a BaseService which has all the CRUD operations, delegating to a BaseDAO injected in it.

    Apart from CRUD, almost everything else has separate logic for the business logic and for the database-specific operations. And another thing - you can have a transaction span multiple database operations by annotating the service-layer methods with @Transactional

    0 讨论(0)
  • 2020-12-08 08:12

    Right now, your service layer is trivial because your service is a trivial wrapping around database accesses. Is that all the app is? If not, when you start building the non-trivial parts, your service layer will expand.

    0 讨论(0)
  • 2020-12-08 08:22

    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.

    0 讨论(0)
  • 2020-12-08 08:23

    The key is the transactional behavior. If you don't have a service layer, where will you demarcate transactions?

    • in the presentation layer: that's not where transaction demarcation belongs, and you wouldn't be able to use declarative transaction demarcation
    • in the DAO layer: you would not be able to create a customer and its contact (for example) in a single transaction, because it would use two different DAOs

    Moreover, you want your UI layer as simple as possible, and the business code (which sometimes is much more complex than sinply calling a DAO method) isolated in specific components. This allows

    • unit testing the UI layer by mocking the service layer
    • unit testing the service layer (the business code) by mocking the DAO layer
    0 讨论(0)
提交回复
热议问题