Extend SimpleJpaRepository

Viewed 11059

I'm using Spring Boot, when I want to extend SimpleJpaRepository like this interface:

public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>{}

and this implementation:

public class BaseRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements BaseRepository<T, ID>
{
    private final EntityManager entityManager;

    public BaseRepositoryImpl(Class<T> domainClass, EntityManager entityManager)
    {
        super(domainClass, entityManager);
        this.entityManager = entityManager;
    }
}

I got the following error:

Could not autowire. No beans of 'Class<T>' type found.

How can I resolve it?

2 Answers

When trying to make an implementation of JpaRepository through extending SimpleJpaRepository, it is important that spring knows you are doing this. By default spring will try to create a SimpleJpaRepository, even if you extend it. Therefore your new implementation of the SimpleJpaRepository will not be populated, created or even remotely available. Therefore all repositories extending your new custom repository will not be created either.

To solve this problem, one should add some repository config. More specifically you need to provide a repositoryBaseClass in the @EnableJpaRepositories annotation; e.g.

@Configuration
@EnableJpaRepositories(
    repositoryBaseClass = RepositoryImpl.class
)

Usually you already have some config class to provide your DataSource-bean, EntityManager-bean and/or JpaTransactionManager-bean. As a general best-practice I suggest placing it over there.

Sometimes spring gets a little confused when you do this and still doesn't manage to find your newly defined repositoryBaseClass. In that case, help the spring repository autowirer a little and also provide a basepackage, e.g.

@Configuration
@EnableJpaRepositories(
    repositoryBaseClass = RepositoryImpl.class,
    basePackages = {
        "be.your.company.your.path.to.your.repositories"
    }
)

Related