Search code examples
javaspringspring-bootspring-data-jpaspring-data

Spring Boot Repository of an interface


Is there any possibility of creating a repository based on an interface in Spring Boot Data? I made this code, in which Medicamento is an interface that many models implements it, but it didn't work out:

public interface MedicamentoRepository extends JpaRepository<Medicamento, Long> {
    public <T extends Medicamento> List<Medicamento> findItens(Class<T> type);
}

Thank you!


Solution

  • With Spring Data JPA, Spring is responsible for generating the implementation and register it as a Spring managed component. All you have to do is configure it properly by adding @EnableJpaRepositories on your Spring configuration class and specifying the package where are your repository interfaces.

    All the basic methods like findOne, findAll, delete, ... are already provided by the CrudRepository interface (and JpaRepository), so you don't need to add them in your interface.

    If you need to add specific methods, then Spring will generate the implementation based on the name of your method and parameters (like findByName where name is a field of your entity) or using the @Query annotation.

    For a better understanding of how Spring Data JPA works and all the available features, check their doc : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/