如何使用spring boot和spring数据访问实体管理器

rob*_*del 15 spring-data spring-data-jpa spring-boot

当我们使用spring boot和spring数据时,如何访问存储库中的实体管理器?

否则,我需要将我的大查询放在注释中,我宁愿有一些清楚的东西......然后是长文本.

Nit*_*ora 17

您将定义一个CustomRepository来处理此类方案.考虑一下你CustomerRepository扩展了默认的spring数据JPA接口JPARepository<Customer,Long>

CustomCustomerRepository使用自定义方法签名创建新接口.

public interface CustomCustomerRepository {
    public void customMethod();
}
Run Code Online (Sandbox Code Playgroud)

CustomerRepository使用扩展接口CustomCustomerRepository

public interface CustomerRepository extends JpaRepository<Customer, Long>, CustomCustomerRepository{

}
Run Code Online (Sandbox Code Playgroud)

创建一个名为CustomerRepositoryImplimplements 的实现类CustomerRepository.在这里你可以注入EntityManager使用@PersistentContext.命名约定在这里很重要.

public class CustomerRepositoryImpl implements CustomCustomerRepository {

    @PersistenceContext
    private EntityManager em;

    @Override
    public void customMethod() {

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我收到此错误`没有找到类型 Customer 的属性 customMethod` 我需要做任何配置吗? (3认同)
  • CustomerRepositoryImpl 类应该实现 CustomCustomerRepository 而不是 CustomerRepository 因为 CustomCustomerRepository 的唯一方法需要实现 (2认同)
  • @AvikAggarwal 公共类 CustomerRepositoryImpl 实现 CustomCustomerRepository { 私有最终 EntityManager 实体管理器; 公共 CustomerRepositoryImpl(EntityManager 实体管理器) { this.entityManager = 实体管理器; } } (2认同)