spring事务管理
1.事务添加到javaEE三层架构里面的Service层(业务逻辑层)
2.spring事务管理API
①提供一个接口,代表事务管理器,这个接口针对不同框架提供不同的实现类
声明式事务管理的使用(xml方式配置)
1.在spring配置文件中配置事务管理器
2.配置文件中开启事务注解(先引入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:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="spring"></context:component-scan> <!--引入外部属性文件--> <context:property-placeholder location="classpath:/jdbc.properties"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" > <property name="driverClassName" value="${jdbc.driverClassName}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--创建jdbcTemplate对象--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <!--注入dataSource属性--> <property name="dataSource" ref="dataSource"></property> </bean> <!--创建事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入数据源--> <property name="dataSource" ref="dataSource"></property> </bean> <!--开启事务注解--> <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> </beans>
在类添加@Transactional注解,表示类中的所有方法都添加事务,也可以加在某个方法上
事务管理参数配置
1.propagation:事务传播行为,当一个事务方法被另外一个事务方法调用的时候,
2. isolation:事务隔离级别
多个事务之间不会产生影响;
有3个读问题:
①脏读:一个未提交事务读取到另一个未提交事务的数据。
②不可重复读:个未提交事务读取到另一个提交事务的修改的数据。
③虚读
3.timeout:超时,事务需要在一定时间内提交,如果不提交进行回滚,默认值-1,单位秒
4.readOnly:是否只读
5.rollbackFor:回滚,设置出现哪些异常进行事务回滚
6.noRollbackFor:不回滚,设置出现哪些异常不进行事务回滚
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?