@Transactional not working when i throw exception on next line

故事扮演 提交于 2021-02-11 15:13:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!