1.使用注解管理事务:添加如下配置,并在java代码的事务管理方法上添加 @Transactional

<!--配置事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!--启动事务管理器-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

1.1通过xml配置的方式实现事务管理

<!--配置bean-->
<bean class="com.ddf.spring.xmltx.BookShopDaoImpl" name="bookShopDao2">
    <property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>

<bean class="com.ddf.spring.xmltx.service.impl.BookServiceImpl" name="bookService2">
    <property name="bookShopDao" ref="bookShopDao2"></property>
</bean>

<bean class="com.ddf.spring.xmltx.service.impl.CashierImpl" name="cashier2">
    <property name="bookService" ref="bookService2"></property>
</bean>

<!--配置事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager2">
    <property name="dataSource" ref="dataSource"></property>
</bean>

<!--配置事务属性-->
<tx:advice id="txAdvice" transaction-manager="transactionManager2">
    <tx:attributes>
        <!--<tx:method name="purchase" propagation="REQUIRES_NEW"/>-->
        <tx:method name="get*" read-only="true"/>
        <tx:method name="find*" read-only="true"/>
        <tx:method name="*"/>
    </tx:attributes>
</tx:advice>

<!--配置事务切点,并把事务切入点和事务属性关联起来-->
<aop:config>
    <aop:pointcut id="txPointcut" expression="execution(* com.ddf.spring.xmltx.service.*.*(..))"></aop:pointcut>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"></aop:advisor>
</aop:config>

 

2.事务的传播行为

  -事务传播属性可以在 @Transactional 注解的 propagation 属性中定义,默认情况下为 REQUIRED, 即使用调用方法的事务

  

  -REQUIRES_NEW: 使用自己的事务, 调用的事务方法的事务被挂起。

  

3.使用 isolation 指定事务的隔离级别, 最常用的取值为 READ_COMMITTED

4.使用 readOnly 指定事务是否为只读. 表示这个事务只读取数据但不更新数据, 这样可以帮助数据库引擎优化事务. 若真的事一个只读取数据库值的方法, 应设置 readOnly=true

5.使用 timeout 指定强制回滚之前事务可以占用的时间.  

posted on 2018-09-10 15:42  超级蛋蛋饭  阅读(64)  评论(0编辑  收藏  举报