扩展 SimpleJpaRepository

Ali*_*... 5 java spring spring-boot

我正在使用 Spring Boot,当我想像SimpleJpaRepository这个接口一样扩展时:

public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>{}
Run Code Online (Sandbox Code Playgroud)

和这个实现:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Could not autowire. No beans of 'Class<T>' type found.
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

Joh*_*esB 12

JpaRepository当尝试通过扩展实现时SimpleJpaRepository,重要的是 spring 知道你正在这样做。默认情况下,spring 会尝试创建一个SimpleJpaRepository,即使你扩展它。因此,您的新实现SimpleJpaRepository将不会被填充、创建,甚至不会远程可用。因此,也不会创建扩展新的自定义存储库的所有存储库。

为了解决这个问题,应该添加一些存储库配置。更具体地说,您需要repositoryBaseClass@EnableJpaRepositories注释中提供 a; 例如

@Configuration
@EnableJpaRepositories(
    repositoryBaseClass = RepositoryImpl.class
)
Run Code Online (Sandbox Code Playgroud)

通常你已经有一些配置类来提供你的DataSource-bean、EntityManager-bean 和/或JpaTransactionManager-bean。作为一般最佳实践,我建议将其放置在那里。

有时,当你这样做时,spring 会有点困惑,并且仍然无法找到你新定义的repositoryBaseClass. 在这种情况下,请为 spring 存储库自动装配器提供一些帮助,并提供一个基础包,例如

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

Run Code Online (Sandbox Code Playgroud)

  • 哈哈,我记得当我做出这个答案时,我自己也经历了相当长的寻找解决方案的过程。很高兴我能帮上忙!快乐编码! (2认同)

Rah*_*ngh 2

制作一个扩展 JpaRepository 的接口

对于例如 -

public interface Repository extends JpaRepository<Entity,Integer>,RepositoryCustom // this is our custom repository{


}
Run Code Online (Sandbox Code Playgroud)

存储库自定义是一个接口

public interface RepositoryCustom {


    List<Entity> getAll(); // define the method signature here


}
Run Code Online (Sandbox Code Playgroud)

实现自定义接口

@Transactional
public class RepositoryImpl implements  RepositoryCustom{

    @PersistenceContext // this will inject em in your class
    private EntityManager entityManager;

    write the method body and return

}
Run Code Online (Sandbox Code Playgroud)

请记住存储库命名约定。如果接口名称是 Repository 。那么自定义接口应命名为 Repository,实现应命名为 Repository