如何使用 XML 配置 Spring Data JPA

Posted

技术标签:

【中文标题】如何使用 XML 配置 Spring Data JPA【英文标题】:How to configure Spring Data JPA using XML 【发布时间】:2014-09-22 20:37:56 【问题描述】:

我正在阅读“用于 Web 应用程序的专业 Java - Nicholas S. Williams”一书 本书示例对 Spring Data JPA 有以下配置:

@Bean
public DataSource customerSupportDataSource()

    JndiDataSourceLookup lookup = new JndiDataSourceLookup();
    return lookup.getDataSource("jdbc/CustomerSupport");


@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()

    Map<String, Object> properties = new Hashtable<>();
    properties.put("javax.persistence.schema-generation.database.action",
            "none");
    properties.put("hibernate.ejb.use_class_enhancer", "true");

    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabasePlatform("org.hibernate.dialect.mysql5InnoDBDialect");

    LocalContainerEntityManagerFactoryBean factory =
            new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(adapter);
    factory.setDataSource(this.customerSupportDataSource());
    factory.setPackagesToScan("com.wrox.site.entities",
            "com.wrox.site.converters");
    factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
    factory.setValidationMode(ValidationMode.NONE);
    factory.setLoadTimeWeaver(this.loadTimeWeaver); // TODO: remove when SPR-10856 fixed
    factory.setJpaPropertyMap(properties);
    return factory;


@Bean
public PlatformTransactionManager jpaTransactionManager()

    return new JpaTransactionManager(
            this.entityManagerFactoryBean().getObject()
    );

但我一直在使用 XML 进行配置,我不知道如何仅将其转换为 XML,我目前有这个

<jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/test"/>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="myEmf" />
</bean>

<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="myDataSource" />
    <property name="packagesToScan" value="com.test" />
</bean>

谁能指导我如何转换它?

谢谢

【问题讨论】:

【参考方案1】:

如果你想通过 XML 配置来配置 Spring Data JPA(并使用书中描述的配置),你必须按照以下步骤操作:

    配置数据源 bean。 配置实体管理器工厂 bean。 配置事务管理器 bean。 启用注释驱动的事务管理。 配置 Spring Spring Data JPA。

应用上下文配置(applicationContext-persistence.xml)文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jpa="http://www.springframework.org/schema/data/jpa"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/jpa 
    http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

  <!-- Configure the data source bean -->
  <jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/CustomerSupport"/>

  <!-- Create default configuration for Hibernate -->
  <bean id="hibernateJpaVendorAdapter" 
    class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>

  <!-- Configure the entity manager factory bean -->
  <bean id="entityManagerFactory" 
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
    <!-- Set JPA properties -->
    <property name="jpaProperties">
      <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
        <prop key="javax.persistence.schema-generation.database.action">none</prop>
        <prop key="hibernate.ejb.use_class_enhancer">true</prop>
      </props>
    </property>
    <!-- Set base package of your entities -->
    <property name="packagesToScan" value="foo.bar.model"/>
    <!-- Set share cache mode -->
    <property name="sharedCacheMode" value="ENABLE_SELECTIVE"/>
    <!-- Set validation mode -->
    <property name="validationMode" value="NONE"/>
  </bean>

  <!-- Configure the transaction manager bean -->
  <bean id="transactionManager" 
    class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
  </bean>

  <!-- Enable annotation driven transaction management -->
  <tx:annotation-driven/>

  <!-- 
    Configure Spring Data JPA and set the base package of the 
    repository interfaces 
  -->
  <jpa:repositories base-package="foo.bar.repository"/>
</beans>

【讨论】:

感谢 pkainulainen,我已经准备好所有上下文和 xml 文件。我想要的是 XML 中给定 java 配置的精确翻译。例如: public DataSource customerSupportDataSource() JndiDataSourceLookup lookup = new JndiDataSourceLookup();返回lookup.getDataSource("jdbc/CustomerSupport"); xml 将是: 不客气。我更新了答案以匹配书中描述的配置。我没有测试,但它应该工作。一件事,配置类是否有 loadTimeWeaver 字段?如果是这样,您应该将完整的 Java 配置类添加到您的问题中。如果你这样做,我也可以将加载时间编织器添加到 XML 配置中。另外,请注意 XML 配置使用旧的模式版本。您可能还想更新它们。 你说得对,现在我需要LoadTimeWeaver,但是这本书的源码不见了,有什么建议吗? 抱歉,我花了一些时间来回答这个问题(电子邮件在我的收件箱中丢失了)。无论如何,我只会使用默认的 LoadTimeWeaver(不要配置它)。 @pkainulainen 我尝试根据我自己的问题调整您的答案:Spring Data configuration - hibernate.properties not found,但我无法 - 是否可以为嵌入式数据源(jdbc:embedded-database)而不是@987654324 @?【参考方案2】:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.thought.service.*" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="generateDdl" value="true" />
            <property name="showSql" value="false" />
            <property name="database" value="MYSQL" />
        </bean>
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.temp.use_jdbc_metadata_defaults">false</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
    
<bean id="transactionSupport" class="com.thought.service.common.database.TransactionSupport" />
        
<bean id="transactionTemplate" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="proxyInterfaces">
        <list> 
    <value>com.thought.service.common.database.TransactionTemplate</value>
        </list>
    </property>
    <!-- <property name="proxyTargetClass" value="false" />   -->
    <property name="transactionManager" ref="transactionManager" />
    <property name="target" ref="transactionSupport" />
    <property name="transactionAttributes">
        <props>
            <prop key="save">PROPAGATION_REQUIRES_NEW,-java.lang.Exception</prop>
        </props>
    </property>
</bean>
public class TransactionSupport implements TransactionTemplate 
    
    public void save(PersistenceHandler persistanceHandler, ModelTemplate model) throws Exception 
        persistanceHandler.save(model);
    
    

public interface TransactionTemplate 
    
    public void save(PersistenceHandler persistanceHandler, ModelTemplate model) throws Exception;
            

public abstract class PersistenceHandler 
        
    /**
     * Method to implement the actual transaction controlled database operations
     * @param model @code ModelTemplate
     * 
     * @throws Exception
     */
    public abstract void save(ModelTemplate model) throws Exception;
                

【讨论】:

在您的帖子中添加一些解释。检查here

以上是关于如何使用 XML 配置 Spring Data JPA的主要内容,如果未能解决你的问题,请参考以下文章

如何使用基于类的配置设置具有不同基础包、transactionManagerRef 的多个 Spring Data JPA?

spring Data solr依赖文件 和xml配置文件

如何使用 spring-data-neo4j-cross-store 在 neo4j 和 postgres 之间的部分 NodeEntity 上支持跨存储持久性?

如何配置 IntelliJ HQL 控制台以使用 Spring Boot

spring-boot配置Redis工具类

Java 配置 /j_spring_security_check 未找到