TransactionStatus接口是事务的状态,它描述了某个时间点上事务的状态信息。具体如下:
事务的并发问题
在实际应用过程中,数据库是要被多个用户所同时访问的。在多个事务同时使用相同数据时,可能会出现并发问题,具体如下:
事务的隔离级别
为了避免事务并发问题的发生,在标准SQL规范中,定义了4个隔离级别,不同的隔离级别对事务的处理不同。
- 读未提交(一级)
一个事务在执行过程中,既可以访问其他事务未提交的新插入的数据,又可以访问未提交的修改数据。如果一个事务已经开始写数据,则另外一个事务则不允许同时进行写操作,但允许其他事务读此行数据。此隔离级别可防止丢失更新。
- 读已提交(二级)
一个事务在执行过程中,既可以访问其他事务成功提交的新插入的数据,又可以访问成功修改的数据。读取数据的事务允许其他事务继续访问该行数据,但是未提交的写事务将会禁止其他事务访问该行。此隔离级别可有效防止脏读。
- 可重复读(三级)
一个事务在执行过程中,可以访问其他事务成功提交的新插入的数据,但不可以访问成功修改的数据。读取数据的事务将会禁止写事务(但允许读事务),写事务则禁止任何其他事务。此隔离级别可有效的防止不可重复读和脏读。
- 序列化(四级)
提供严格的事务隔离。它要求事务序列化执行,事务只能一个接着一个地执行,但不能并发执行。此隔离级别可有效的防止脏读、不可重复读和幻读。
- 注意:
注意:虽然事务的隔离级别越高,越能保证数据库的完整性和一致性,但并发时越高的级别对性能的影响也越大。在实际开发中,通常将数据库的隔离级别设置为2级,即Read Committed。它既能防止脏读,又有良好的并发性。虽然这种隔离级别会导致不可重复读、幻读和第二类丢失更新问题,但这些问题可以通过在应用程序中使用悲观锁和乐观锁来控制。
事务的传播行为
上述方法中,事务的传播行为是指在同一个方法中,不同操作前后所使用的事务。传播行为有很多种,具体如下表所示:
- 如何实现Spring的声明式事务管理?
Spring的声明式事务管理可以通过两种方式来实现,一种是基于XML的方式,另一种是基于Annotation的方式。
基于XML方式的声明式事务
实例
<?xml version="1.0" encoding="UTF-8"?><beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:aop=“http://www.springframework.org/schema/aop”
xmlns:context=“http://www.springframework.org/schema/context”
xmlns:tx=“http://www.springframework.org/schema/tx”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
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/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
">
<context:component-scan base-package=“cn.*”/>
<tx:advice transaction-manager=“transactionManager” id=“txAdvice”>
tx:attributes
<tx:method name=“*” propagation=“REQUIRED” isolation=“DEFAULT” read-only=“true”/>
</tx:attributes>
</tx:advice>
aop:config
<aop:pointcut id=“myPointcut” expression=“execution(* cn.service..(…))”/>
<aop:advisor advice-ref=“txAdvice” pointcut-ref=“myPointcut”/>
</aop:config>
基于Annotation方式的声明式事
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
务
实例
<?xml version="1.0" encoding="UTF-8"?><beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:aop=“http://www.springframework.org/schema/aop”
xmlns:context=“http://www.springframework.org/schema/context”
xmlns:tx=“http://www.springframework.org/schema/tx”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
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/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
">