代码改变世界

Spring管理hibernate的事务的方法

2012-07-30 10:59  Patrick.Lee  阅读(334)  评论(0编辑  收藏  举报

转自:http://yhjhappy234.blog.163.com/blog/static/31632832200952362948131/

在某个方法前面添加事务标注

如,用银行存款进行买股票,则存款减少

@Transactional(propagation=Propagation.REQUIRED,rollbackFor=StockException.class)
    public void buyStock(String accName, double amt, String stockName) throws StockException {
        // TODO Auto-generated method stub
        Account a = accountDAO.findByName(accName);
        a.setBalance(a.getBalance() - amt);
        accountDAO.save(a);
        if(1==1)
            throw new StockException();
        Stock s = stockDAO.findByName(stockName);
        s.setQty(s.getQty() + amt/s.getPrice());
        stockDAO.save(s);
    }

 

配置文件设置:

    <!-- dataSource,配置数据源 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/tarena</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>1234</value>
        </property>
    </bean>
    <!-- SessionFactory -->
    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="mappingResources">
            <list>
                <value>entity/Account.hbm.xml</value>
                <value>entity/Stock.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            </props>
        </property>
    </bean>


    <!-- HibernateTransactionManager 配置事务管理-->
    <bean id="myTransactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="mySessionFactory" />
        </property>
    </bean>


    <!-- DAO配置dao接口实现类 -->
    <bean id="abstactDAO" abstract="true">
        <property name="sessionFactory" ref="mySessionFactory" />
    </bean>
    <bean id="accountDAO" class="dao.impl.AccountDAOHibernateImpl"
        parent="abstactDAO" />
    <bean id="stockDAO" class="dao.impl.StockDAOHibernateImpl"
        parent="abstactDAO" />


    <!-- service配置业务接口实现类 -->
    <bean id="stockProcessService"
        class="service.impl.StockProcessServiceSpringImpl3">
        <property name="accountDAO" ref="accountDAO" />
        <property name="stockDAO" ref="stockDAO" />
    </bean>

    <!--配置事务-->
    <tx:annotation-driven transaction-manager="myTransactionManager" />

 

2.不用标注、代理,

方法的实现就是照常写,配置文件有所变化

    <!-- dataSource -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/tarena</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>1234</value>
        </property>
    </bean>
    <!-- SessionFactory -->
    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="mappingResources">
            <list>
                <value>entity/Account.hbm.xml</value>
                <value>entity/Stock.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
            </props>
        </property>
    </bean>
    <!-- HibernateTransactionManager -->
    <bean id="myTransactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref bean="mySessionFactory" />
        </property>
    </bean>
    <!-- DAO配置抽象父类,被dao接口实现类继承 -->
    <bean id="abstactDAO" abstract="true">
        <property name="sessionFactory" ref="mySessionFactory" />
    </bean>

    <bean id="accountDAO" class="dao.impl.AccountDAOHibernateImpl"
        parent="abstactDAO" />
    <bean id="stockDAO" class="dao.impl.StockDAOHibernateImpl"
        parent="abstactDAO" />
    <!-- serviceTarget -->
    <bean id="stockProcessServiceTarget"
        class="service.impl.StockProcessServiceSpringImpl">
        <property name="accountDAO" ref="accountDAO" />
        <property name="stockDAO" ref="stockDAO" />
    </bean>
    <!-- 配置事务代理 -->
    <bean id="stockProcessService"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager">
            <ref bean="myTransactionManager" />
        </property>
        <property name="target">
            <ref bean="stockProcessServiceTarget" />
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="find*">PROPAGATION_SUPPORTS,readOnly</prop>
                <prop key="open*">PROPAGATION_REQUIRED</prop>
                <prop key="buyStock">PROPAGATION_REQUIRED,-StockException</prop>
            </props>
        </property>
    </bean>

 

 

方法二:

<?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:jee="http://www.springframework.org/schema/jee"
 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
 http://www.springframework.org/schema/jee
 http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-2.5.xsd
 http://www.springframework.org/schema/aop
 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
 default-lazy-init="true">

 <context:component-scan base-package="com.foo" />
 
    <!--数据库配置文件-->
 <context:property-placeholder location="/WEB-INF/database_properties/wms-sql.properties" />

    <!--JDBC连接池-->
 <bean id="wmsDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
  destroy-method="close" dependency-check="none">
  <property name="driverClass">
   <value>${datasource.driverClassName}</value>
  </property>
  <property name="jdbcUrl">
   <value>${datasource.url}</value>
  </property>
  <property name="user">
   <value>${datasource.username}</value>
  </property>
  <property name="password">
   <value>${datasource.password}</value>
  </property>
  <property name="acquireIncrement">
   <value>${c3p0.acquireIncrement}</value>
  </property>
  <property name="initialPoolSize">
   <value>${c3p0.initialPoolSize}</value>
  </property>
  <property name="minPoolSize">
   <value>${c3p0.minPoolSize}</value>
  </property>
  <property name="maxPoolSize">
   <value>${c3p0.maxPoolSize}</value>
  </property>
  <property name="maxIdleTime">
   <value>${c3p0.maxIdleTime}</value>
  </property>
  <property name="idleConnectionTestPeriod">
   <value>${c3p0.idleConnectionTestPeriod}</value>
  </property>
  <property name="maxStatements">
   <value>${c3p0.maxStatements}</value>
  </property>
  <property name="numHelperThreads">
   <value>${c3p0.numHelperThreads}</value>
  </property>
  <property name="acquireRetryAttempts" value="30" />
  <property name="breakAfterAcquireFailure" value="true" />
  <property name="testConnectionOnCheckout" value="false" />
 </bean>

    <!--加载hibernate3-->
 <bean id="wmssessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource">
   <ref local="wmsDataSource"></ref>
  </property>
  <property name="mappingDirectoryLocations">
   <list>
    <value>classpath:com/foo/tpl/pojo</value>
    <value>classpath:com/foo/backPlant/pojo/commons</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">
     ${hibernate.dialect}
    </prop>
    <prop key="hibernate.show_sql">
     ${hibernate.show_sql}
    </prop>
    <prop key="connection.provider_class">
     org.hibernate.connection.C3P0ConnectionProvider
    </prop>
    <prop key="hibernate.jdbc.fetch_size">
     ${hibernate.jdbc.fetch_size}
    </prop>
    <prop key="hibernate.jdbc.batch_size">
     ${hibernate.jdbc.batch_size}
    </prop>
    <prop key="hibernate.cache.use_second_level_cache">true</prop>
    <prop key="hibernate.cache.use_query_cache">true</prop>
    <prop key="hibernate.cache.provider_class">
     org.hibernate.cache.EhCacheProvider
    </prop>
   </props>
  </property>
 </bean>
 
 <bean id="wmstransactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory" ref="wmssessionFactory" />
 </bean>
 
 <!-- 配置事务特性-->
 <tx:advice id="wmstxadvice" transaction-manager="wmstransactionManager">
  <tx:attributes>
   <tx:method name="save*" propagation="REQUIRED" rollback-for="RuntimeException" />
   <tx:method name="del*"  propagation="REQUIRED" rollback-for="RuntimeException" />
   <tx:method name="edit*" propagation="REQUIRED" rollback-for="RuntimeException" />
   <tx:method name="*" read-only="true" />
  </tx:attributes>
 </tx:advice>
 
 <!--配置那些类的方法进行事务管理-->
 <aop:config>
  <aop:pointcut id="wmsallManagerMethod"
   expression="execution(* com.foo.backPlant.dao.login.impl.MakeLoginInfoDaoImpl.*(..))||execution(* com.foo.*.service.*.impl.*.*(..))||execution(* com.foo.*.web.dwr.*.*(..))" />
  <aop:advisor advice-ref="wmstxadvice" pointcut-ref="wmsallManagerMethod" />
 </aop:config>

 <!--注射登陆认证dao-->
 <bean id="MakeLoginInfoDaoImpl" class="com.foo.backPlant.dao.login.impl.MakeLoginInfoDaoImpl">
  <property name="sessionFactory">
   <ref bean="wmssessionFactory" />
  </property>
 </bean>
 
 <!-- 注射登陆认证Dao-->
 <!-- 注射实验实例service-->
 <!-- <bean id="taskAssignmentListWmsServiceImpl"-->
 <!--
  class="com.foo.backPlant.service.experiment.impl.TaskAssignmentListWmsServiceImpl"
  >
 -->
 <!-- </bean>-->
 <!-- 注射实验实例service-->
</beans>