Spring声明式事务

来源:互联网 发布:java jetty 编辑:程序博客网 时间:2024/06/06 01:30

spring中对事务的管理是spring的一大特点
主要分为声明式事务和编程式事务。一般来说声明式事务已经可以帮我们解决大多数问题。

声明式事务处理

需要导入aop和tx的命名空间

<?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: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/aop        http://www.springframework.org/schema/aop/spring-aop.xsd        http://www.springframework.org/schema/tx        http://www.springframework.org/schema/tx/spring-tx.xsd">

配置文件

<!-- dataSource配置略了 --><!-- 声明式事务管理 -->    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <property name="dataSource" ref="dataSource"/>    </bean>    <!--配置事务通知  -->    <tx:advice id="txAdvice" transaction-manager="txManager">        <tx:attributes>            <!--配置哪些方法使用什么样的事务,配置事务的传播特性  -->            <tx:method name="add"  propagation="REQUIRED"/>            <tx:method name="update"  propagation="REQUIRED"/>            <tx:method name="insert"  propagation="REQUIRED"/>            <tx:method name="delete"  propagation="REQUIRED"/>            <tx:method name="remove*"  propagation="REQUIRED"/>            <tx:method name="get"  read-only="true"/>        </tx:attributes>    </tx:advice>    <aop:config>        <aop:pointcut expression="execution(* cn.sxt.dao.impl.*.*(..))" id="pointcut"/>        <aop:advisor advice-ref="txAdvice"  pointcut-ref="pointcut"/>    </aop:config>    <!-- 声明式事务配置结束 -->

代码解释:

  1. 首先配置事务管理类,注入数据源,然后配置事务通知,再用aop配置哪些方法需要引入事务通知。事务通知里面的是sqlsession的哪些方法需要开启事务,事务的传播特性是什么
  2. propagation="REQUIRED"就是当前横切的方法sqlsession调用这个方法的时候如果没有事务,则开始事务,如果有,则支持这个事务
  3. <tx:method name="get" read-only="true"/>设置为只读的话说明只能读取,不能写入,当前事务不支持写入,如果横切的方法里面sqlsession调用了get,又调用了insert等相关写入的操作就会报错,当前事务就失败了,控制台也不会显示查询到的数据。
原创粉丝点击