Reputation: 309
How should be separated Repository and Service? IMHO clients (e.g. 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?
Upvotes: 3
Views: 2130
Reputation: 3599
Services should implement (business) logic and possibly modify entities according to that logic. If your service layer is only a thin wrapper around repositories, i.e. 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.
Upvotes: 6