Spring Transaction中是否需要exception处理?
我对使用Transaction进行exception处理有疑问。 为了清楚说明我的问题,我想展示我的配置:
活动事务类是:
@Transactional public class CustomerService extends BaseService implements ICustomerService { @Transactional(readOnly = true) public Customer getCustomerById(String id) { return getDaoProvider().getCustomerDao().getCustomerById(id); } @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class }) public void addNewCustomer(CustomerDTO customerDTO) { Customer customer = new Customer(); customer.setCustomerId(customerDTO.getCustomerId()); customer.setCustomerName(customerDTO.getCustomerName()); customer.setActive(customerDTO.isActive()); getDaoProvider().getCustomerDao().save(customer); } }
我的疑惑在于addNewCustomer
方法。 我已经设置了rollbackFor = { Throwable.class }
。
它是如何工作的?
我还需要显式处理exception,如:
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class }) public boolean addNewCustomer(CustomerDTO customerDTO) { Customer customer = new Customer(); customer.setCustomerId(customerDTO.getCustomerId()); customer.setCustomerName(customerDTO.getCustomerName()); customer.setActive(customerDTO.isActive()); try { getDaoProvider().getCustomerDao().save(customer); } catch (Throwable throwable) { return false; } return true; }
强制我通过删除customer表中的列来创建exception,但是该exception不是try-catch块中的catch,而是我可以从我调用了addNewCustomer
方法的托管bean中捕获该exception。
这是Spring文档的摘录
在其默认配置中,Spring Framework的事务基础结构代码仅在运行时未经检查的exception情况下标记用于回滚的事务; 也就是说,抛出的exception是RuntimeException的实例或子类。 (错误也将 – 默认情况下 – 导致回滚)。 从事务方法抛出的已检查exception不会导致在默认配置中回滚。
你设置rollbackFor = Throwable.class,现在Spring将回滚任何Exception / Error。 默认情况下,无论我们是否喜欢,Spring将仅针对RuintimeException进行回滚,否则进行提交
Spring框架只抛出RuntimeExceptions,从技术上讲,你永远不必捕获任何exception。
- 为什么Java编译器允许在throws部分中列出exception,该方法无法抛出exception
- 运行时/已检查/未检查/错误/exception之间的差异
- 有效地使用UncaughtExceptionHandler
- 使用Strutsvalidation框架进行error handling的问题
- 检查某个exception类型是否是嵌套exception中的原因(原因等等)的最佳方法?
- 在Java中,是使用throws Exception而不是抛出多个特定exception的好习惯?
- 如何在解析CSV行中的空位置时避免触发ArrayIndexOutOfBoundsException?
- 捕获更一般类型的exception是否好?
- Java套接字:重试Connection Refusedexception的最佳方法?