【问题标题】:How to access entity manager with spring boot and spring data如何使用 Spring Boot 和 Spring Data 访问实体管理器
【发布时间】:2015-09-01 15:54:59
【问题描述】:

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

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

【问题讨论】:

    标签: spring-boot spring-data spring-data-jpa


    【解决方案1】:

    您将定义一个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() {
        
        }
    }
    

    【讨论】:

    • CustomerRepositoryImpl 类应该实现 CustomCustomerRepository 而不是 CustomerRepository 作为 CustomCustomerRepository 需要实现的唯一方法
    • 这个 CustomCustomerRepositoryImpl 是否可以在没有 customMethod() 的情况下工作?
    • 我收到此错误No property customMethod found for type Customer 我需要做任何配置吗?
    • 如果你得到错误“No property customMethod found for type Customer”删除注解@PersistenceContext并通过CustomRepositoryImpl的构造函数注入entityManager对象
    • @AvikAggarwal 公共类 CustomerRepositoryImpl 实现 CustomCustomerRepository { private final EntityManager entityManager;公共 CustomerRepositoryImpl(EntityManager entityManager) { this.entityManager = entityManager; } }
    【解决方案2】:

    如果您有许多存储库要处理,并且您在 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 方法是一个示例方法,用于使用分离的实体实例、对其执行刷新并返回要在声明性事务上下文中应用于刷新实体的自定义函数的结果。您也可以添加其他方法,包括查询方法...

    注意 演示代码在收到第一个无声的反对票时进行了简化。仍然鼓励进一步的投票者(如果有的话)花一分钟时间至少放弃一行评论,因为无声投票有什么意义吗? :)

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 2021-07-12
      • 2019-05-17
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2016-12-03
      相关资源
      最近更新 更多