Spring:声明式事物

本文介绍了Spring中声明式事务的配置和使用,包括配置数据源、SqlSessionFactory、事务管理器,以及通过AOP实现事务的织入。在配置中,展示了如何设置事务的传播特性,并针对`add`、`delete`和`query`方法指定了不同的事务属性,如`REQUIRED`和`read-only`。
摘要由CSDN通过智能技术生成

1、声明式事物

1、回顾事物
在这里插入图片描述

在这里插入图片描述

2、配置事物的传播特性propagation: 有7种

在这里插入图片描述
在这里插入图片描述

3、官方是把事物配到方法上面,我们一般用横切的方式去做

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--dataSource-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncode=UTF-8&amp;serverTimezone=GMT%2B8"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--绑定mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/lan/mapper/*.xml"/>
    </bean>
    <!--配置声明式事物-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
<!--        <constructor-arg ref="dataSource" />-->
    </bean>
    <!--结合AOP实现事物的织入-->
    <!--配置事物通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!--给那些方法配置事物-->
            <!--配置事物的传播特性 :propagation 7-->
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <!--read-only="true:表示只读-->
            <tx:method name="query" read-only="true"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事物切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.lan.mapper.UserMapper.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

</beans>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值