https://blog.csdn.net/sinat_34338162/article/details/80755930
方式一、注解方式
1.@EnableTransactionManagement
@Slf4j
@SpringBootApplication
@MapperScan(value="com.test.mybatisplus.mapper")
@ImportResource(locations = {"classpath:spring-test.xml"})
@EnableApolloConfig
@EnableTransactionManagement
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
//NettyServer.run(8080);
//log.info("======netty服务已经启动========");
}
}
2.(spring中的@Transactional 放在类级别 和 方法级别 上一样效果)
@Transactional
@Override
public int transactionTest(PressInfoEntity pressInfoEntity, LambdaUpdateWrapper<PressInfoEntity> updateWrapper) {
int flag=this.baseMapper.update(pressInfoEntity,updateWrapper);
List aaa =new ArrayList();
aaa.get(6);
return flag;
}
方式二、配置全局事务
1.添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.新建TransactionAdviceConfig.java
package com.test.mybatisplus.config;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;
/**
* @Description 配置全局事务
* @project
* @author:hf
* @date:
*/
@Aspect
@Configuration
public class TransactionAdviceConfig {
private static final String AOP_POINTCUT_EXPRESSION="execution(* com.test.mybatisplus.service.impl.*.*(..))";
@Bean
public TransactionInterceptor txAdvice(TransactionManager transactionManager){
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();
source.addTransactionalMethod("save*",txAttr_REQUIRED);
source.addTransactionalMethod("insert*",txAttr_REQUIRED);
source.addTransactionalMethod("delete*",txAttr_REQUIRED);
source.addTransactionalMethod("update*",txAttr_REQUIRED);
source.addTransactionalMethod("remove*",txAttr_REQUIRED);
source.addTransactionalMethod("get*",txAttr_REQUIRED_READONLY);
source.addTransactionalMethod("query*",txAttr_REQUIRED_READONLY);
source.addTransactionalMethod("select*",txAttr_REQUIRED_READONLY);
return new TransactionInterceptor(transactionManager,source);
}
//定义切入点使用什么意见操作,具体意见参见txAdvice()方法定义
@Bean
public Advisor txAdviceAdvisor(TransactionManager transactionManager){
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut,txAdvice(transactionManager));
}
}
3.具体方法
@Transactional
@RequestMapping(value ="/updateBy2" , method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
public String updateBy2(){
LambdaUpdateWrapper<PressInfoEntity> updateWrapper = new LambdaUpdateWrapper<PressInfoEntity>()
.eq(PressInfoEntity::getId,157);
PressInfoEntity pressInfoEntity = PressInfoEntity.builder().press("我被updateBy2修改了!").build();
transactionService.update2(pressInfoEntity,updateWrapper);
return "success";
}
/**
* 配置全局事务
* @return
*/
@RequestMapping(value ="/updateBy1" , method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
public String updateBy1(){
LambdaUpdateWrapper<PressInfoEntity> updateWrapper = new LambdaUpdateWrapper<PressInfoEntity>()
.eq(PressInfoEntity::getId,157);
PressInfoEntity pressInfoEntity = PressInfoEntity.builder().press("我被updateBy1修改了!").build();
transactionService.update1(pressInfoEntity,updateWrapper);
return "success";
}
3.
默认spring事务只在发生未被捕获的 runtimeexcetpion时才回滚。
spring aop 异常捕获原理:被拦截的方法需显式抛出异常,并不能经任何处理,这样aop代理才能捕获到方法的异常,才能进行回滚,默认情况下aop只捕获runtimeexception的异常,但可以通过 。
配置来捕获特定的异常并回滚
在service的方法中不使用try catch 或者在catch中最后加上throw new runtimeexcetpion(),这样程序异常时才能被aop捕获进而回滚
解决方案:
方案1.例如service层处理事务,那么service中的方法中不做异常捕获,或者在catch语句中最后增加throw new RuntimeException()语句,以便让aop捕获异常再去回滚,并且在service上层(webservice客户端,view层action)要继续捕获这个异常并处理
方案2.在service层方法的catch语句中增加:TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();语句,手动回滚,这样上层就无需去处理异常(现在项目的做法,方法上需要加
@Override
public int update2(PressInfoEntity pressInfoEntity, LambdaUpdateWrapper<PressInfoEntity> updateWrapper) {
int flag=0;
try{
flag=this.baseMapper.update(pressInfoEntity,updateWrapper);
//异常,回滚
List aaa =new ArrayList();
aaa.get(6);
}catch (Exception e){
log.error("update2:"+e.toString());
//不会回滚
}
return flag;
}
@Override
public int update1(PressInfoEntity pressInfoEntity, LambdaUpdateWrapper<PressInfoEntity> updateWrapper) {
int flag=0;
try{
flag=this.baseMapper.update(pressInfoEntity,updateWrapper);
//异常,回滚
List aaa =new ArrayList();
aaa.get(6);
}catch (Exception e){
log.error("update1:"+e.toString());
throw new RuntimeException();
//会回滚
}
return flag;
}