如何将JpaTemplate的使用从Spring 3.2迁移到4.1.4?

Jim*_*hrs 5 spring jpa spring-4

当前,我们已经配置并运行了Spring 3.2.9.RELEASE(已经运行了几年),需要迁移到4.1.4.RELEASE。我们有一个抽象的DAO类,它扩展org.springframework.orm.jpa.support.JpaDaoSupport了以下内容:

  • org.springframework.orm.jpa.JpaCallback
  • org.springframework.orm.jpa.JpaTemplate

我已经看到JpaDaoSupport在Spring 4中已将其删除。我已删除了对Jpa *类的引用,并替换为

@PersistenceContext 
protected EntityManager theEntityManager;
Run Code Online (Sandbox Code Playgroud)

并在中找到我们DAO中的方法引用(如findByNamedParams()JpaDaoSupport,然后将其复制到我们的DAO中。

完成上述更改后,我们便可以编译我们的代码,但是当涉及到运行我们的JUnit测试时,我们applicationContext-test.xml

<bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="abstractDAO" abstract="true" class="my.company.package.AbstractDAO">
    <property name="jpaTemplate" ref="jpaTemplate" />
</bean>

<bean id="genericDAO" parent="abstractDAO" class="my.company.package.GenericDAO" />
<bean id="securityDAO" parent="abstractDAO" class="my.company.package.SecurityDAOImpl" />
Run Code Online (Sandbox Code Playgroud)

基本上错误是没有的类引用org.springframework.orm.jpa.JpaTemplate。我们如何JpaTemplate在Spring 4.1.4中替换此配置?

请注意,我选择的是这段代码,而不是最初配置系统的代码。另外,我对Spring及其配置设置还很陌生。

Oli*_*ohm 3

  1. 确保AbstractDAO迁移到EntityManagerAPI 并@PersistenceContext在注入点(通常是 setter)上使用。
  2. 使用启用注释配置<context:annotation-config />或配置 aPersistenceAnnotationBeanPostProcessor以启用将其注入EntityManager到 DAO 中。您可以完全摆脱 bean 定义AbstractDAO。请注意,如果您已<context:component-scan />在某处激活,那么这应该已经可以开箱即用了。

PS:如果您要迁移,您可能会考虑立即升级到 Spring 4.2。如果这不是一个选项,请使用最新的 Spring 4.1 版本(撰写本文时为 4.1.7)。