在需要进行事务控制的方法上加上@Transactional
注解,当发生异常时,整个事务会进行回滚。
@Transactional(rollbackFor = Exception.class)
@Override
public boolean removeByIds(Collection<? extends Serializable> idList) {
//do something
}
事务回滚失效情况:
- 如果代码里面进行了catch异常捕获, 处理业务逻辑后, 需要抛出异常, 否则事务不会回滚.
- 类内部调用类内部@Transactional标注的方法不会开启事务, 事务管理是基于动态代理对象的代理逻辑实现, 该调用方式是通过this对调调用, 所以不生效
- 私有方法@Transactional不生效
/**
* 事务失效案例2
*/
@Component
public class TestServiceImpl implements TestService {
@Transactional
public void insertTestInnerInvoke() {
// do something
}
public void testInnerInvoke(){
// 这种情况事务不会生效
insertTestInnerInvoke();
}
}
@Transactional注解有propagation属性, 决定事务传播机制
Propagation propagation() default Propagation.REQUIRED;
Propagation | Desc |
---|---|
REQUIRED | Support a current transaction, create a new one if none exists |
SUPPORTS | Support a current transaction, execute non-transactionally if none exists. |
MANDATORY | Support a current transaction, throw an exception if none exists. |
REQUIRES_NEW | Create a new transaction, and suspend the current transaction if one exists |
NOT_SUPPORTED | Execute non-transactionally, suspend the current transaction if one exists |
NEVER | Execute non-transactionally, throw an exception if a transaction exists |
NESTED | Execute within a nested transaction if a current transaction exists, behave like REQUIRED otherwise |