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?
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).