spring-data-jpa 如何使用 Spring Boot 和Spring Data 访问实体管理器

cngwdvgl  于 2022-11-10  发布在  Spring
关注(0)|答案(2)|浏览(191)

在使用Sping Boot 和Spring Data时,如何才能访问存储库中的Entity Manager
否则,我将需要把我的大查询放在一个注解中。我更喜欢有比长文本更清晰的东西。

lsmd5eda

lsmd5eda1#

您可以定义一个CustomRepository来处理这样的场景。
使用自定义方法签名创建一个新接口CustomCustomerRepository

public interface CustomCustomerRepository {
    public void customMethod();
}

使用CustomCustomerRepository扩展CustomerRepository接口

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

}

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

public class CustomCustomerRepositoryImpl implements CustomCustomerRepository {

    @PersistenceContext
    private EntityManager em;

    @Override
    public void customMethod() {

    }
}
kqhtkvqz

kqhtkvqz2#

如果你有很多仓库需要处理,并且你对EntityManager的需求并不是针对任何特定的仓库,那么可以在一个helper类中实现各种EntityManager功能,可能是这样的:

@Service
public class RepositoryHelper {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public <E, R> R refreshAndUse(
            E entity,
            Function<E, R> usageFunction) {
        em.refresh(entity);
        return usageFunction.apply(entity);
    }

}

这里的refreshAndUse方法是一个示例方法,用于使用分离的实体示例,对其执行刷新,并返回一个自定义函数的结果,该结果将应用于声明性事务上下文中的刷新实体。

相关问题