Spring事务注解配置

一,spring基于注解式的事务配置方法:@Transactional 

1.xml配置

<?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-2.5.xsd  
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd  
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">  
    
   <tx:annotation-driven transaction-manager="txManager"/>  
   <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
   <property name="dataSource" ref="dataSource"/>  
  </bean>  
</beans>

2.常用事物注解:

2.1 readOnly 

主要用于查询中:@Transactional(readOnly = true)

用于客户代码只读但不修改数据的情形,只读事务用于特定情景下的优化,比如使用Hibernate的时候。
默认为读写事务

2.2 rollbackFor

对于增删改查时的回滚,默认情况下checked exceptions不进行回滚,仅unchecked exceptions(即RuntimeException的子类)才进行事务回滚,需直接抛出RuntimeException及其子类
@Transactional(rollbackFor = { RuntimeException.class })
	public Result<Integer> insert(RequestPara request) throws RuntimeException{}

2.3 枚举型:Propagation,可选的传播性设置->如果在开始当前事务之前,一个事务上下文已经存在,此时有若干选项可以指定一个事务性方法的执行行为

2.4 枚举型:Isolation,可选的隔离性级别(默认值:ISOLATION_DEFAULT)->若干个并发的事务之间的隔离程度

2.5 timeout,以秒为单位->一个事务所允许执行的最长时间,如果超过该时间限制但事务还没有完成,则自动回滚事务

2.6 noRollbackFor 遇到时必须不回滚

扫描二维码关注公众号,回复: 2498594 查看本文章

二,spring boot事物管理注解方式

1.启动类main上添@EnableTransactionManagement //如果mybatis中service实现类中加入事务注解(等同于<tx:annotation-driven />,dataSource 框架会自动为我们注入),需要此处添加该注解,当然也包括其他2个注解

(@MapperScan("com.company.mapper") //扫描的是mapper.xml中namespace指向值的包位置),@SpringBootApplication

2.在需要的事物的service方法或类上加入注解@Transactional

3.导入的jar

 <!-- Spring Boot Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>{version}</version>
</dependency>

猜你喜欢

转载自blog.csdn.net/anyeoo/article/details/80393139