1、加入spring-jdbc.jar包

2、配置数据源

3、配置spring事务管理器,spring的事务出现在业务层。

    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <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="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    

4.加入事务包,spring-tx.jar.

(1)基于xml配置的事务

(2)在xml中声明命名空间

xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd

(3)

 <aop:config>
    <aop:pointcut id="productServiceMethods"
            expression="execution(* product.ProductService.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="productServiceMethods"/>
  </aop:config>

  <tx:advice id="txAdvice" transaction-manager="myTxManager">
    <tx:attributes>
      <tx:method name="increasePrice*" propagation="REQUIRED"/>
      <tx:method name="someOtherBusinessMethod" propagation="REQUIRES_NEW"/>
      <tx:method name="*" propagation="SUPPORTS" read-only="true"/>
    </tx:attributes>
  </tx:advice>

propagation:事务的传播属性,在方法为increasePrice开头的方法中需要在一个事务中运行,指定required

注意:spring事务,只有在运行时异常时才会发生回滚,如果其他的非运行时异常不会回滚

这种情况可以修改在

 <tx:method name="increasePrice*" propagation="REQUIRED"/>
指定rollback-for="java.lang.exception"

5、基于注解的事务

 (1)在xml中开启事务注解,指定事务管理器名字

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

(2)在要执行事务的类或者方法上边添加@Transactional标注

@Transactional
    public void show(){
        userDao.showUser();
    }

(3)在只读事务中,加入readonly=true,查找的时候用只读可以提高效率

    @Transactional(readOnly=true)
    public void show(){
        userDao.showUser();
    }

 

posted on 2015-03-05 18:29  猿类的进化史  阅读(362)  评论(0编辑  收藏  举报