jta+spring4+hibernate5/jpa2配置

时间:2022-05-06 20:36:09
  • spring配置
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
    <context:component-scan base-package="com"/>
    <!--<aop:aspectj-autoproxy proxy-target-class="true"/>-->
    <!--配置数据源与数据库连接池 -->
    <bean id="ds1" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
        <property name="uniqueResourceName" value="ds1"/>
        <property name="xaDataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"/>
        <property name="xaProperties">
            <props>
                <prop key="user">root</prop>
                <prop key="password">1853</prop>
                <prop key="url">jdbc:mysql://127.0.0.1:3306/world?useUnicode=true&amp;characterEncoding=UTF-8&amp;useFastDateParsing=false&amp;pinGlobalTxToPhysicalConnection=true</prop>
            </props>
        </property>
        <property name="maxPoolSize" value="10"/>
        <property name="minPoolSize" value="1"/>
    </bean>
    <!--配置事务管理器的内部内容-->
    <bean id="userTransactionService" class="com.atomikos.icatch.config.UserTransactionServiceImp" init-method="init" destroy-method="shutdownForce">
        <constructor-arg>
            <!-- IMPORTANT: specify all Atomikos properties here -->
            <props>
                <prop key="com.atomikos.icatch.service">
                    com.atomikos.icatch.standalone.UserTransactionServiceFactory
                </prop>
            </props>
        </constructor-arg>
    </bean>
    <!--配置一个事务管理器-->
    <bean id="transactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close" depends-on="userTransactionService">
        <property name="forceShutdown">
            <value>false</value>
        </property>
    </bean>
    <!--配置一个用户事务实现-->
    <bean id="userTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
        <property name="transactionTimeout" value="300" />
    </bean>
    <!--_________________________jpa需要自己重写一个JtaPlatfom______________________________________________-->
    <!--实例化一个EntityManagerFactory-->
    <!--该bean的作用是将spring中配置的tranactionManager,usertransaction注入到AtomikosJtaPlatfom中的一个静态域中,实现spring事务管理器与hibernate的事务管理器一致!!!!-->
    <bean id="ajp" class="com.test.AtomikosJtaPlatfom">
        <property name="tm" ref="transactionManager"/>
        <property name="ut" ref="userTransaction"/>
    </bean>
    <!--强制要求先实例化ajp,这样能够保证hibernate使用了spring初始化后的transactionManager与usertransaction-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" depends-on="ajp">
        <property name="packagesToScan" value="com"/>
        <property name="persistenceUnitName" value="PU1"/>
        <property name="jtaDataSource" ref="ds1"/>
        <!-- 方言,鸡肋-->
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true"/>
                <property name="showSql" value="true"/>
                <property name="database" value="MYSQL"/>
            </bean>
        </property>
        <property name="jpaProperties">
            <props>
                <!--以下属性必须加有hibernate-->
                <prop key="hibernate.show_sql">true</prop>
                <!--必要的-->
                <prop key="hibernate.transaction.coordinator_class">jta</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!--由于spring没有为jpa提供jta管理注入,所以需要手工配置一个JtaPlatfom-->
                <prop key="hibernate.transaction.jta.platform">com.test.AtomikosJtaPlatfom</prop>
                <!--自动为所有关键字的类名/实例域添加``-->
                <prop key="hibernate.auto_quote_keyword">true</prop>
            </props>
        </property>
    </bean>
    <!--____________________________sessionfactory不需要配置jtaPlatform,因为spring提供了支持___________________________________________-->
    <!--实例化一个SessionFactory,getBean()将返回一个SessionFactory实例-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="packagesToScan" value="com"/>
        <property name="annotatedPackages" value="com"/>
        <property name="dataSource" ref="ds1"/>
        <!--spring自动配置jtaplatfom,但是jpa需要自己配置-->
        <property name="jtaTransactionManager" ref="transactionManager"/>
        <property name="hibernateProperties">
            <props>
                <!--以下属性必须加有hibernate-->
                <prop key="hibernate.show_sql">true</prop>
                <!--必要的-->
                <prop key="hibernate.transaction.coordinator_class">jta</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <!--自动为所有关键字的类名/实例域添加``-->
                <prop key="hibernate.auto_quote_keyword">true</prop>
            </props>
        </property>
    </bean>
    <!--_______________________________________________________________________-->

    <bean id="jtaTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="rollbackOnCommitFailure" value="true"/>
        <property name="transactionManager" ref="transactionManager"/>
        <property name="userTransaction" ref="userTransaction"/>
    </bean>
    <!--编程式事务模板-->
    <bean id="tansactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="jtaTransactionManager"/>
    </bean>
    <!--非注解的声明式事务-->
    <!--<tx:advice id="transactionInterceptor" transaction-manager="jtaTransactionManager">-->
        <!--<tx:attributes>-->
            <!--<tx:method name="doPost" propagation="REQUIRED"/>-->
            <!--<tx:method name="*" propagation="SUPPORTS"/>-->
        <!--</tx:attributes>-->
    <!--</tx:advice>-->
    <!--<aop:config>-->
        <!--<aop:advisor advice-ref="transactionInterceptor" pointcut="execution(* *..S.*(..))"/>-->
    <!--</aop:config>-->
    <!--注解的声明式事务,使用@Transactionals注解bean,可在类上或方法上使用-->
    <!--<tx:annotation-driven transaction-manager="jtaTransactionManager"/>-->
    <!--<context:component-scan base-package="com">-->
        <!--<context:include-filter type="assignable" expression="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>-->
    <!--</context:component-scan>-->
</beans>
  • AtomikolsJtaPlatfom,必须先由spring注入hibernate才能正常工作.
package com.test;

import org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.transaction.*;

/** * @author doggy * Created on 16-5-15. */
public class AtomikosJtaPlatfom extends AbstractJtaPlatform {
    private static UserTransaction ut;
    private static TransactionManager tm;
    @Override
    protected TransactionManager locateTransactionManager() {
        return tm;
    }

    @Override
    protected UserTransaction locateUserTransaction() {
        return ut;
    }

    public UserTransaction getUt() {
        return ut;
    }

    public void setUt(UserTransaction ut) {
        AtomikosJtaPlatfom.ut = ut;
    }

    public TransactionManager getTm() {
        return tm;
    }

    public void setTm(TransactionManager tm) {
        AtomikosJtaPlatfom.tm = tm;
    }
}
  • 样例
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try(PrintWriter writer = resp.getWriter()) {
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
            SessionFactory sessionFactoryBean = (SessionFactory) applicationContext.getBean("sessionFactory");
            TransactionTemplate template = (TransactionTemplate)applicationContext.getBean("tansactionTemplate");
            template.execute(new TransactionCallback<Object>() {
                @Override
                public Object doInTransaction(TransactionStatus transactionStatus) {
                    try{
                        Session session = sessionFactoryBean.getCurrentSession();
                        Fuck f = new Fuck();
                        session.save(f);
                    }catch(RuntimeException re){
                        re.printStackTrace();
                    }
                    //回滚事务
                    transactionStatus.setRollbackOnly();
                    return null;
                }
            });
            writer.println("love you");
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
  • 依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.xls*</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

    <groupId>fish</groupId>
    <artifactId>fish</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.5.RELEASE</version>
        </dependency>

        <!-- struts2 -->
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.3.20</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-spring-plugin</artifactId>
            <version>2.3.20</version>
        </dependency>

        <!-- hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.1.0.Final</version>
        </dependency>
        <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.1.0.Final</version>
        </dependency>


        <!-- jta and mysql -->
        <dependency>
            <groupId>com.atomikos</groupId>
            <artifactId>transactions-jdbc</artifactId>
            <version>4.0.1</version>
        </dependency>
        <!-- http://mvnrepository.com/artifact/com.atomikos/transactions-hibernate3 -->
        <dependency>
            <groupId>com.atomikos</groupId>
            <artifactId>transactions-hibernate3</artifactId>
            <version>4.0.3</version>
        </dependency>


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <!-- for json -->
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.3.7</version>
        </dependency>

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>

        <!-- joda -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-catalina</artifactId>
            <version>8.0.33</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.1.6</version>
        </dependency>

    </dependencies>
</project>