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或者是否设置了自定义的回滚异常