SpringBoot事务的使用以及开启

简介: SpringBoot事务的使用以及开启
 
//启动类上加
@MapperScan(basePackages = "com.xxx.mapper.*")
@SpringBootApplication
@EnableScheduling
@EnableTransactionManagement  //注解生效就加
public class SysWebApplication extends SpringBootServletInitializer
 
//这个是测试
------------------------- 添加修改删除 -----------------------------
@RequestMapping(value = "/save", method = RequestMethod.POST )
@Log("查看系统日志列表")
@Transactional(propagation = Propagation.REQUIRED)
public ResultBean save(){
demoMapper.insert(new Demo(11L,"1"));
demoMapper.insert(new Demo(12L,"1"));
demoMapper.insert(new Demo(13L,"1"));
return ResultBean.ok();
}
 
------------------------- 查询 -----------------------------
@Transactional(propagation = Propagation.SUPPORTS)
@RequestMapping(value = "/list", method = RequestMethod.GET )
@Log("查看系统日志列表")
public ResultBean get(HttpServletRequest request, HttpServletResponse response) throws IOException {
 
List all = demoService.seleDemo();
 
try{
 
return ResultBean.ok(all);
}catch (Exception e){
e.printStackTrace();
}
 
return null;
}

传播行为

所谓事务的传播行为是指,如果在开始当前事务之前,一个事务上下文已经存在,此时有若干选项可以指定一个事务性方法的执行行为。

我们可以看 org.springframework.transaction.annotation.Propagation 枚举类中定义了6个表示传播行为的枚举值:

public enum Propagation {  
    REQUIRED(0),
    SUPPORTS(1),
    MANDATORY(2),
    REQUIRES_NEW(3),
    NOT_SUPPORTED(4),
    NEVER(5),
    NESTED(6);
}

  • REQUIRED :如果当前存在事务,则加入该事务;如果当前没有事务,则创建一个新的事务。
  • SUPPORTS :如果当前存在事务,则加入该事务;如果当前没有事务,则以非事务的方式继续运行。
  • MANDATORY :如果当前存在事务,则加入该事务;如果当前没有事务,则抛出异常。
  • REQUIRES_NEW :创建一个新的事务,如果当前存在事务,则把当前事务挂起。
  • NOT_SUPPORTED :以非事务方式运行,如果当前存在事务,则把当前事务挂起。
  • NEVER :以非事务方式运行,如果当前存在事务,则抛出异常。
  • NESTED :如果当前存在事务,则创建一个事务作为当前事务的嵌套事务来运行;如果当前没有事务,则该取值等价于 REQUIRED

指定方法:通过使用 propagation 属性设置,例如:

@Transactional(propagation = Propagation.REQUIRED)
相关文章
|
Java Spring
springboot的自动配置原理
springboot的自动配置原理
|
Java Spring
SpringBoot中事务执行原理分析(三)
SpringBoot中事务执行原理分析(三)
159 0
|
1月前
|
Dart 前端开发 JavaScript
springboot自动配置原理
Spring Boot 自动配置原理:通过 `@EnableAutoConfiguration` 开启自动配置,扫描 `META-INF/spring.factories` 下的配置类,省去手动编写配置文件。使用 `@ConditionalXXX` 注解判断配置类是否生效,导入对应的 starter 后自动配置生效。通过 `@EnableConfigurationProperties` 加载配置属性,默认值与配置文件中的值结合使用。总结来说,Spring Boot 通过这些机制简化了开发配置流程,提升了开发效率。
74 17
springboot自动配置原理
|
Java 关系型数据库 MySQL
SpringBoot手动提交事务
SpringBoot手动提交事务
711 0
|
9月前
|
Java Spring 容器
SpringBoot的自动配置原理(一)
SpringBoot的自动配置原理(一)
|
9月前
|
Java Spring
SpringBoot 开启事务Spring事务常用
SpringBoot 开启事务Spring事务常用
54 0
|
XML 设计模式 Java
SpringBoot中事务执行原理分析(一)
SpringBoot中事务执行原理分析(一)
165 1
|
9月前
|
Java API 数据库
SpringBoot - 优雅的处理【长事务】
SpringBoot - 优雅的处理【长事务】
224 0
|
9月前
|
Java 关系型数据库 MySQL
SpringBoot中事务执行原理分析(五)
SpringBoot中事务执行原理分析(五)
70 0
|
9月前
|
SQL Java 数据库连接
SpringBoot中事务执行原理分析(六)
SpringBoot中事务执行原理分析(六)
242 0

热门文章

最新文章