Spring声明式事务

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等相关写入的操作就会报错,当前事务就失败了,控制台也不会显示查询到的数据。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值