Spring笔记:事务管理
Spring中常用的是结合AOP的声明式事务管理,也就是不用改变当前已有的代码。而且也比较简单,只需要在Spring的xml中改动4个地方即可。
<?xml version="1.0" encoding="UTF-8"?>
<!-- 改动点1:增加事务支持tx -->
<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
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 使用Spring的数据源替换MyBatis的配置,这里使用Spring提供的JDBC,
这样就不用在MyBatis的xml中来配置数据源了-->
<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&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- 改动点2:配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 事务管理器需要配置数据源,即用户名、密码等数据库连接信息 -->
<constructor-arg ref="dataSource"/>
</bean>
<!-- 改动点3:结合AOP使用事务管理 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 给数据库哪些操作方法配置事务,propagation默认就是REQUIRED,表示如果没有事务,则新建事务,
其他的值可以在网上查一下,所以这里不显式指定propagation也可以 -->
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 改动点4:配置事务切入 -->
<aop:config>
<!-- 配置切入点,这里配置的是mapper包下所有的所有方法 -->
<aop:pointcut id="txPointcut" expression="execution(* com.yun.mapper.*.*(..))"/>
<!-- 给每个切入点配置事务 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律