Spring Boot:开启全局事务
一.properties配置文件(数据库相关配置省略)
#------------------------事务相关配置---------------------------# transactional.method.required=save*,delete*,update*,exec*,set*,insert*,add*,imp* transactional.method.readOnly=get*,query*,find*,select*,list*,is*,count*
二.配置类 OssTransactionAdviceConfiguration
/** * @author wen.jie * @Classname OssTransactionAdviceConfiguration * @Description Oss全局事务控制 * @Date 2020/7/11 * 参考:https://www.cnblogs.com/hnusthuyanhua/p/11796365.html */ @Component @Aspect public class OssTransactionAdviceConfiguration { @Autowired private TransactionManager transactionManager; //指定事务处理范围 private static final String POINTCUT_EXPRESSION = "execution(* com.topcheer..service..*(..))"; ////////////////////--------从properties中读取相关配置-------///////////////////////////// @Value("#{'${transactional.method.required}'.split(',')}") private List<String> requiredList; @Value("#{'${transactional.method.readOnly}'.split(',')}") private List<String> readOnlyList; @Bean public TransactionInterceptor txAdvice() { DefaultTransactionAttribute txAttr_REQUIRED = new DefaultTransactionAttribute(); txAttr_REQUIRED.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); DefaultTransactionAttribute txAttr_REQUIRED_READONLY = new DefaultTransactionAttribute(); txAttr_REQUIRED_READONLY.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); txAttr_REQUIRED_READONLY.setReadOnly(true); NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource(); Map<String,TransactionAttribute> nameMap = new LinkedHashMap<>(); requiredList.forEach(r->nameMap.put(r,txAttr_REQUIRED)); readOnlyList.forEach(r->nameMap.put(r,txAttr_REQUIRED_READONLY)); source.setNameMap(nameMap); return new TransactionInterceptor(transactionManager, source); } @Bean public Advisor txAdviceAdvisor() { AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression(POINTCUT_EXPRESSION); return new DefaultPointcutAdvisor(pointcut, txAdvice()); } }
三.测试
@Service public class UserService { @Autowired private UserMapper userMapper; public void insertTest(){ List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("rid",3)); User user = new User(); user.setAccount("asdasd"); user.setPassword("asasa"); user.setRid(3); user.setUid(100); userMapper.insert(user); int a = 1/0; } }
测试结果:
数据库并没有插入对应数据,事务回滚了。