java 手动事务回滚_通过手动抛自定义异常实现spring事务回滚

本文介绍了如何在Spring中手动控制事务回滚,特别是在使用自定义异常时确保事务能够正确回滚。通过在service层的方法上添加`@Transactional(rollbackFor=MyException.class)`,当方法抛出`MyException`异常时,Spring会自动回滚事务。示例代码展示了在插入数据时,如果插入失败则抛出自定义异常,从而触发事务回滚。
摘要由CSDN通过智能技术生成

spring默认事务管理:默认当一个方法出现RunTimeException(运行期异常)时会自动回滚事务。

有些时候,我们需要从业务上对spring事务进行控制,这时候,如果用spring的默认事务管理,事务没有回滚就达不到我们所期望的结果。

demo用的spring+mybatis+springmvc+mysql。

解决方法:

applicationContext-service.xml 中增删改方法加上rollback-for="MyException",当方法抛出自定义异常被spring接收,会回滚事务。

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

http://www.springframework.org/schema/beans/spring-beans-4.2.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-4.2.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-4.2.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-4.2.xsd

http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-4.2.xsd

http://code.alibabatech.com/schema/dubbo

http://code.alibabatech.com/schema/dubbo/dubbo.xsd">

View Code

MyException 自定义异常类:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

public class MyException extendsException {privateString message;publicString getMessage() {returnmessage;

}public voidsetMessage(String message) {this.message =message;

}publicMyException(String message) {super();this.message =message;

}publicMyException() {super();

}public MyException(String message, Throwable cause, boolean enableSuppression, booleanwritableStackTrace) {super(message, cause, enableSuppression, writableStackTrace);

}publicMyException(String message, Throwable cause) {super(message, cause);

}publicMyException(Throwable cause) {super(cause);

}

View Code

ProMapper.java

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值