Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Repository and Service layer

Tags:

I looked through some related questions but still I don't see much difference between the a repository and a service layer. So given the example I suppose it should look like this , if not please tell me why?

public interface ProductRepository extends CrudRepository<Product, Long>{

    public List<Product> findByName(String name);
    public List<Product> findByPrice(Double price);
}

public interface ProductService {

    public List<Product> findAll();
    public Product findById(Long id);
    public Product save(Product product);
    public void delete(Product product);
    public List<Product> findByName(String name);
    public List<Product> findByPrice(Double price);
}

and the implementation of the ProductService would use the ProductRepository to implement the methods. As I understand from http://docs.spring.io/spring-data/jpa/docs/1.3.0.RELEASE/reference/html/jpa.repositories.html the queries for methods from the repository are auto generated. In my example the methods are repeated in the repository and Service, so please explain what/why needs to be changed?

like image 512
April Avatar asked Apr 09 '14 12:04

April


2 Answers

All your business logic should be in the Service Layer.

Any access to the Database (any storage) should go to the Repository Layer.

Lets take an Example. You have to save an entity(Person). But before saving the Person you want to make sure that the Person's FirstName does not exist already.

So the validation part should go to the business layer.

In the service Layer

PersonRepository repository; 
public Person save(Person p){
   Person p = findByName(p.getName();
   if (p != null){
          return some customException();
   }
   return repository.save(p); 
}

public Person findByName(String name){
     return repository.findByName(name);
}

And in your Repository Layer just concentrate on DB Operation.

You could have done this in Repository Layer it self. Assume you have implemented this in your Repository then your save method always check before saving (some time you may not required to do).

like image 118
Mani Avatar answered Nov 15 '22 21:11

Mani


Repository Layer gives you additional level of abstraction over data access. Repository layer exposes basic CRUD operations.

Service layer exposes business logic, which uses repository.

You can read a more detailed answer here: https://stackoverflow.com/a/5049454/1446006

like image 30
Martin Avatar answered Nov 15 '22 23:11

Martin