【发布时间】:2015-09-01 15:54:59
【问题描述】:
使用 Spring Boot 和 Spring Data 时如何访问存储库中的 Entity Manager?
否则,我需要将我的大查询放在注释中。我希望有比长文本更清晰的内容。
【问题讨论】:
标签: spring-boot spring-data spring-data-jpa
使用 Spring Boot 和 Spring Data 时如何访问存储库中的 Entity Manager?
否则,我需要将我的大查询放在注释中。我希望有比长文本更清晰的内容。
【问题讨论】:
标签: spring-boot spring-data spring-data-jpa
您将定义一个CustomRepository 来处理此类情况。考虑你有CustomerRepository,它扩展了默认的spring数据JPA接口JPARepository<Customer,Long>
使用自定义方法签名创建一个新接口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() {
}
}
【讨论】:
No property customMethod found for type Customer 我需要做任何配置吗?
如果您有许多存储库要处理,并且您在 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 方法是一个示例方法,用于使用分离的实体实例、对其执行刷新并返回要在声明性事务上下文中应用于刷新实体的自定义函数的结果。您也可以添加其他方法,包括查询方法...
注意 演示代码在收到第一个无声的反对票时进行了简化。仍然鼓励进一步的投票者(如果有的话)花一分钟时间至少放弃一行评论,因为无声投票有什么意义吗? :)
【讨论】: