Difference between Repository and Service Layer?

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


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