Creating a Repository

Just an Interface

With Spring Data JPA you declare an interface; at startup Spring creates an implementation (backed by the EntityManager) and registers it as a bean:

package in.shopease.repository;

import in.shopease.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ProductRepository extends JpaRepository<Product, Long> {
    //                                               entity ^   ^ id type
}
@Service
public class ProductService {
    private final ProductRepository productRepository;

    public ProductService(ProductRepository productRepository) {   // constructor injection
        this.productRepository = productRepository;
    }
}

Note: No @Repository annotation is needed on the interface. Spring Boot scans for repository interfaces in the package of the main class and below.

The Repository Hierarchy

Repository<T, ID>                 marker interface
   +-- CrudRepository<T, ID>       save, findById, findAll, count, delete ...
   |     +-- ListCrudRepository    same, but returns List instead of Iterable
   +-- PagingAndSortingRepository  findAll(Sort), findAll(Pageable)
         |
 JpaRepository<T, ID>  = ListCrud + ListPagingAndSorting + JPA extras
                         (flush, saveAndFlush, saveAll, deleteAllInBatch, getReferenceById)

Tip: Use JpaRepository by default. It returns List, which is easier to work with than Iterable.