Spring’s @Transactional does not rollback on checked exceptions

We’re using the Spring Framework in most of our applications (and thus also in the Catalysts Platform) and are really satisfied with it.

One of the big advantages is the the declarative transaction handling using the @Transactional attribute.

import org.springframework.transaction.Transactional;

@Transactional
public class MyService implements IMyService {
public List getResults () {
// do something
}

public void foo() {
throw new java.lang.UnsupportedOperationException();
}

public void bar() {
throw new java.lang.Exception();
}
}
That simple annoation on class managed by a Spring ApplicationContext causes all method calls onto that service to be bound to a transaction. The transaction is committed after the method call has left the service again and it’s rollbacked for the case an exception is thrown (e.g. after calling the (quite silly) method foo()).

But be careful: Only unchecked exceptions (that is, subclasses of java.lang.RuntimeException) are rollbacked by default. For the case, a checked exception is thrown, the transaction will be committed!

The Spring documentation explains that as follows:

While the EJB default behavior is for the EJB container to automatically roll back the transaction on a system exception (usually a runtime exception), EJB CMT does not roll back the transaction automatically on an application exception (that is, a checked exception other than java.rmi.RemoteException). While the Spring default behavior for declarative transaction management follows EJB convention (roll back is automatic only on unchecked exceptions), it is often useful to customize this.

And that customization can be done very easily by just adding the parameter rollBackFor to the @Transactional attribute:

import org.springframework.transaction.Transactional;

@Transactional(rollbackFor = Exception.class)
public class MyService implements IMyService {
public List getResults () {
// do something
}

public void foo() {
throw new java.lang.UnsupportedOperationException();
}

public void bar() {
throw new java.lang.Exception();
}
}
[color=red]In that case, the transaction will even be be rollbacked on a call to the method bar().[/color]


from : https://www.catalysts.cc/en/wissenswertes/spring-transactional-rollback-on-checked-exceptions/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值