我不理解以下行为:
我有一个方法:
@Transactional
public void processRejection(final Path path) {
try {
//some code here
} catch (final Exception e) {
this.handleException(e));
}
}
它调用以下做saves
的实体,该实体还不存在于数据库中:
void handleException(final Throwable e) {
this.filesMonitoringJpaManager.save(someEntityHere);
throw new Exception(...)
}
现在奇怪的是,当我注释throw new Exception(...)
时,save
工作,但当我取消注释throw new Exception(...)
时,save
不工作,我不知道为什么?
JPA或Hibernate有什么奇怪的行为?是不是我不理解Java异常机制?
@Transactional
用于在出现问题(抛出异常(时回滚。您正在catch
块中保存一个实体,但您正在重新引发一个异常,导致事务性方法回滚。
但您可以指定一个不会导致回滚的异常:
@Transactional(noRollbackFor = {MyException.class})
public void processRejection(final Path path) {
try {
//somecode here whatever
} catch (final Exception e) {
this.handleException(e));
}
}
void handleException(final Throwable e) {
this.filesMonitoringJpaManager.save(someEntityHere);
throw new MyException(...)
}
这适用于org.springframework.transaction.annotation.Transactional
。如果您使用的是javax.transaction.Transactional
,那么您可以通过使用dontRollbackOn
属性来实现它。