【问题标题】:How to implement Spring's @Transactional Annotation using Hibernate, HikariCP and persistence.xml如何使用 Hibernate、HikariCP 和 persistence.xml 实现 Spring 的 @Transactional Annotation
【发布时间】:2017-12-03 23:12:08
【问题描述】:

我需要实现 Spring 的 @Transactional 注释,但我无法这样做。

在过去的 3 周里,我尝试了很多方法,但都没有奏效。

我还需要使用 EntityManager。为了测试 Spring 是否正常工作,我尝试使用 @PersistenceContext 注入 EntityManager(我也尝试使用 @PersistenceUnit 和/与 EntityManagerFactory),但总是得到 nullPointerException。

 @PersistenceContext(unitName = "sistema")
 protected EntityManager entityManager;

基本上我需要知道如何让 spring 的注解起作用,以及如何使用这些技术实现事务管理器:

persitence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="sistema" transaction-type="RESOURCE_LOCAL"> 
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.sis.vo.Person</class>

        <properties>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.connection.autocommit" value="false" />

            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.enable_lazy_load_no_trans" value="false"/>
            <property name="hibernate.show_sql" value="false" />
            <property name="hibernate.format_sql" value="false"/>

            <!-- do I need those? -->
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost/myDatabase?autoReconnect=true&amp;useSSL=false" />
            <property name="hibernate.connection.username" value="myUser" />
            <property name="hibernate.connection.password" value="myPass" />

        </properties>
   </persistence-unit>
</persistence>

spring.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/context/spring-context-4.3.xsd
                    http://www.springframework.org/schema/mvc
                    http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
                    http://www.springframework.org/schema/jee
                    http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
                    http://www.springframework.org/schema/tx
                    http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">


    <context:annotation-config />
    <mvc:annotation-driven />

     <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="poolName" value="sisHikariCP" />
        <property name="connectionTestQuery" value="SELECT 1" />
        <property name="dataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
        <property name="minimumIdle" value="3" />
        <property name="maximumPoolSize" value="100" />
        <property name="idleTimeout" value="740000" />
        <property name="maxLifetime" value="1740000" />
        <property name="leakDetectionThreshold" value="30000" />
        <property name="dataSourceProperties">
            <props>
                <prop key="url">jdbc:mysql://localhost/myDatabase?autoReconnect=true&amp;useSSL=false</prop>
                <prop key="user">myUser</prop>
                <prop key="password">myPass</prop>

                <prop key="prepStmtCacheSize">350</prop>
                <prop key="prepStmtCacheSqlLimit">2048</prop>
                <prop key="cachePrepStmts">true</prop>
                <prop key="useServerPrepStmts">true</prop>
                <prop key="useLocalSessionState">true</prop>
                <prop key="useLocalTransactionState">true</prop>
                <prop key="rewriteBatchedStatements">true</prop>
                <prop key="cacheResultSetMetadata">true</prop>
                <prop key="cacheResultSetMetadata">true</prop>
                <prop key="cacheServerConfiguration">true</prop>
                <prop key="elideSetAutoCommits">true</prop>
                <prop key="maintainTimeStats">false</prop> 
            </props>
        </property>
    </bean>

    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
        <constructor-arg ref="hikariConfig" />
    </bean>

    <bean id="myJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter" ref="myJpaVendorAdapter" />

    </bean>

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

    <tx:annotation-driven transaction-manager="transactionManager"  />


</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>sis</display-name>

    <context-param>
        <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
        <param-value>true</param-value>
    </context-param>
    <welcome-file-list>
        <welcome-file>index.jsf</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>


    <!--  SPRING  -->

    <servlet>
        <servlet-name>Spring Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
                <param-name>contextConfigLocation</param-name>
            <param-value>
                    /WEB-INF/spring.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
</web-app>

DAO

@Repository
public class GenericListDAO<E> {

    @PersistenceContext(unitName = "sistema")
    protected EntityManager entityManager;

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public GenericListDAO() {
    }

    //rest of the code (persist, find, etc)
}

版本:

  • 春季版:4.3.12
  • 休眠版本:5.1.10.Final
  • HikariCP 版本:2.7.3
  • JDK 版本:1.8.0_121
  • Tomcat 版本:8.5.23

谢谢!

【问题讨论】:

  • 顺便说一句,我不需要继续使用 XML。但我需要继续使用 EntityManager。

标签: java spring hibernate hikaricp persistence.xml


【解决方案1】:

这是我用来配置我的事务管理器的东西

<bean id="myDatasource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="myJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="myDatasource" />
    <property name="jpaVendorAdapter" ref="myJpaVendorAdapter" />

</bean>

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

<tx:annotation-driven transaction-manager="transactionManager"  />

entityManagerFactory bean 将使用类路径中的 persistence.xml 创建持久性单元。

更新 像这样获得持久性上下文

@PersistenceContext(unitName="sistema")
protected EntityManager em;

还要确保使用持久性上下文的类使用 @Repository 注释

更新 你能把这个添加到你的web.xml

<!-- The definition of the Root Spring Container shared by all Servlets 
    and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
    classpath:/WEB-INF/spring-root-context.xml
    </param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

现在在spring.xml 旁边创建一个新文件spring-root-context.xml,并将所有与数据库和事务相关的内容移动到spring-root-context.xml

所以spring.xml 将是您的servlet 上下文,spring-root-context.xml 将是您的根上下文。

与控制器相关的任何内容都将转到 spring.xml 所有其他 bean 将转到 spring-root-context.xml

还将&lt;context:component-scan base-package="package.for.genericdao" /&gt; 添加到spring.xmlspring-root-context.xml 中,并将package.for.genericdao 替换为您的基本包名称。

【讨论】:

  • 嗨@Zeronex,谢谢你的回答!使用此配置我仍然无法使用:@PersistenceContext protected EntityManager entityManager; 任何提示?
  • 我仍然无法使用弹簧注释。 =/
  • 如果我将所有数据库和事务相关的东西移到spring-root-context.xml,我的spring.xml 将只有bean 头和&lt;context:annotation-config /&gt;&lt;mvc:annotation-driven /&gt;。对吗?
  • @jNewbie just 在 spring.xml 应该没问题,把你的包给
  • 为了让它发挥作用,我不得不从SpringBeanAutowiringSupport 扩展我的服务。您能否更新您的答案,以便我标记为答案?
最近更新 更多