在使用Spring Boot和Spring Data时,我如何访问存储库中的Entity Manager
?
否则,我将需要将我的大查询放在注释中。我希望有比长文本更清晰的东西。
在使用Spring Boot和Spring Data时,我如何访问存储库中的Entity Manager
?
否则,我将需要将我的大查询放在注释中。我希望有比长文本更清晰的东西。
您可以定义一个CustomRepository
来处理这种情况。假设您有一个扩展默认Spring Data JPA接口JpaRepository<Customer,Long>
的CustomerRepository
。
创建一个新的接口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() {
}
}
如果您有许多存储库需要处理,并且您对 EntityManager
的需求不特定于任何特定的存储库,则可以在单个帮助程序类中实现各种 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
方法是一个示例方法,用于消耗一个分离的实体实例,对其进行刷新,并返回应用于刷新实体的自定义函数的结果,在声明式事务上下文中。您还可以添加其他方法,包括查询方法...
private final EntityManager entityManager; public CustomerRepositoryImpl(EntityManager entityManager) { this.entityManager = entityManager; }
} - cnmuc