springboot事务管理

1、设置SpringBoot事务

springboot项目要使用事务必须要开启@EnableTransactionManagement注解。这个注解有且仅有在启动类上面有一个注解,不能有重复。如下面的代码中:

package com.qlys.security;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.qlys.security.service.impl.RedisCache;


@SpringBootApplication
@EnableFeignClients
@EnableTransactionManagement
@EnableCircuitBreaker
@EnableDiscoveryClient
public class ServiceSecurityAbilityApplication {

	
	
	public static void main(String[] args) {
		SpringApplication.run(ServiceSecurityAbilityApplication.class, args);
	}

}

在启动类中设置了EnableTransactionManagement注解后,下一步就是在需要进行事务处理的方法上面加入对应的@Transactional注解了。这里有一个需要注意的地方,springboot默认对抛出RuntimeException异常的方法进行加滚。因此如果我们需要自定义自己的异常需要在Transactional注解上加入rollbackFor这个属性。如下面的代码就是指定当抛出Exception异常时回滚。

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean insert(AccountModel account) throws Exception {

因此在我们的事务不进行回滚时,尽量检查这二个地方,一个是启动类上面是否启用了事务注解或者是否有重复的启动注解。另一个是事务注解对应的方面上面是否为招聘RuntimeException或者是否设置了自定义的回滚异常

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值