如何使用 spring boot 和 spring 数据访问实体管理器 [英] How to access entity manager with spring boot and spring data

查看:24
本文介绍了如何使用 spring boot 和 spring 数据访问实体管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Spring Boot 和 Spring Data 时,如何访问存储库中的 Entity Manager?

How can I get access to the Entity Manager in the repository when using Spring Boot and Spring Data?

否则,我需要将我的大查询放在注释中.我希望有比长文本更清晰的内容.

Otherwise, I will need to put my big query in an annotation. I would prefer to have something more clear than a long text.

推荐答案

您将定义一个 CustomRepository 来处理此类情况.考虑你有 CustomerRepository 它扩展了默认的 spring 数据 JPA 接口 JPARepository

You would define a CustomRepository to handle such scenarios. Consider you have CustomerRepository which extends the default spring data JPA interface JPARepository<Customer,Long>

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

Create a new interface CustomCustomerRepository with a custom method signature.

public interface CustomCustomerRepository {
    public void customMethod();
}

使用 CustomCustomerRepository

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

}

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

Create an implementation class named CustomerRepositoryImpl which implements CustomerRepository. Here you can inject the EntityManager using the @PersistentContext. Naming conventions matter here.

public class CustomCustomerRepositoryImpl implements CustomCustomerRepository {

    @PersistenceContext
    private EntityManager em;

    @Override
    public void customMethod() {
    
    }
}

这篇关于如何使用 spring boot 和 spring 数据访问实体管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆