在使用Sping Boot 和Spring Data时,如何才能访问存储库中的Entity Manager?否则,我将需要把我的大查询放在一个注解中。我更喜欢有比长文本更清晰的东西。
Entity Manager
lsmd5eda1#
您可以定义一个CustomRepository来处理这样的场景。使用自定义方法签名创建一个新接口CustomCustomerRepository。
CustomRepository
CustomCustomerRepository
public interface CustomCustomerRepository { public void customMethod(); }
使用CustomCustomerRepository扩展CustomerRepository接口
CustomerRepository
public interface CustomerRepository extends JpaRepository<Customer, Long>, CustomCustomerRepository{ }
创建一个名为CustomerRepositoryImpl的实现类来实现CustomerRepository。在这里你可以使用@PersistentContext注入EntityManager。命名约定在这里很重要。
CustomerRepositoryImpl
@PersistentContext
EntityManager
public class CustomCustomerRepositoryImpl implements CustomCustomerRepository { @PersistenceContext private EntityManager em; @Override public void customMethod() { } }
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方法是一个示例方法,用于使用分离的实体示例,对其执行刷新,并返回一个自定义函数的结果,该结果将应用于声明性事务上下文中的刷新实体。
refreshAndUse
2条答案
按热度按时间lsmd5eda1#
您可以定义一个
CustomRepository
来处理这样的场景。使用自定义方法签名创建一个新接口
CustomCustomerRepository
。使用
CustomCustomerRepository
扩展CustomerRepository
接口创建一个名为
CustomerRepositoryImpl
的实现类来实现CustomerRepository
。在这里你可以使用@PersistentContext
注入EntityManager
。命名约定在这里很重要。kqhtkvqz2#
如果你有很多仓库需要处理,并且你对
EntityManager
的需求并不是针对任何特定的仓库,那么可以在一个helper类中实现各种EntityManager
功能,可能是这样的:这里的
refreshAndUse
方法是一个示例方法,用于使用分离的实体示例,对其执行刷新,并返回一个自定义函数的结果,该结果将应用于声明性事务上下文中的刷新实体。