问题
I don't understand the below behavior:
I have a method:
@Transactional
public void processRejection(final Path path) {
try {
//some code here
} catch (final Exception e) {
this.handleException(e));
}
}
which calls the below which does a saves
an entity which doesn't yet exists in the database:
void handleException(final Throwable e) {
this.filesMonitoringJpaManager.save(someEntityHere);
throw new Exception(...)
}
Now the strange is when I comment the throw new Exception(...)
the save
works, but when I uncomment throw new Exception(...)
then the save
doesn't work and I have no clue why?
What strange behavior is that from JPA or Hibernate? Is it something about Java Exception mechanism which I don't understand?
回答1:
@Transactional
is meant to roll back when something goes wrong (an exception is thrown). You're saving an entity in the catch
block, but you're rethrowing an exception causing the transactional method to roll back.
But you can specify an exception, that will not cause rollback:
@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(...)
}
This works for org.springframework.transaction.annotation.Transactional
. If you're using javax.transaction.Transactional
, then you can achieve it by using dontRollbackOn
property.
来源:https://stackoverflow.com/questions/60995945/transactional-not-working-when-i-throw-exception-on-next-line