简体   繁体   中英

How to separate Repository and Service Layers

How should be separated Repository and Service? IMHO clients (eg Controller) should primaly use Service layer instead of Repository as it should be separated from persistance implementation. Single Repository should provide methods of access of only one entity, while methods of Service are able to provide more complex actions, including usage of multiple repositories.

But what to do with rich repositories, that provides not only CRUD methods but much more, like JPARepository from Spring Data? In such implementations there are so many possible methods of fetching objects that duplicating them in Service isn't cool.

So what is the solution for that problem?

A. Duplicate methods in service layer like this

@Service
class XService{

   @Autowired
   private XRepository repository;

   public List<X> findAll(){
        return repository.findAll();
   }
}

B. Simply using repository in controllers (autowired or access method in service)

C. Any other good approach?

Services should implement (business) logic and possibly modify entities according to that logic. If your service layer is only a thin wrapper around repositories, ie only fetching entities as your description suggests, something is wrong with your design.

Often logic is spread throughout the controllers. Identify that logic, extract and encapsulate it in services and restrict Controllers to manage the application's flow, by orchestrating the appropriate services.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM