Define An Extensible Or Generic JPA Repository

Posted on Oct 20, 2024

The @NoRepositoryBean annotation allows to define an extensible / generic JPA repository in Spring Boot:

@NoRepositoryBean
public interface BaseAnimalRepository<T> extends JpaRepository<T, Long>

From the documentation of the @NoRepositoryBean:

This will typically be used when providing an extended base interface for all repositories in combination with a custom repository base class to implement methods declared in that intermediate interface. In this case you typically derive your concrete repository interfaces from the intermediate one but don’t want to create a Spring bean for the intermediate interface.

Otherwise you get an error, because Spring tries to create a bean out of it:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseAnimalRepository' defined in de.dkwr.example.repository.BaseAnimalRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Not a managed type: class java.lang.Object

Want to know more?

Keep on reading and choose one of the related articles. You can also check the home page for my latest thoughts, notes and articles.