Search code examples
springspring-transactionsruntimeexception

Do NOT let transaction rollback for a particular type of RuntimeException


Hi is there a way to let spring transaction NOT rollback after I throw a particular kind of RuntimeException?

I have a class called CustomException extends RuntimeException, I want to do sth before throwing it. But because of the rollback, whatever is done by doSth() is rolled back.

doSth();
throw new CustomException();

I can manage this by changing CustomException from extending RuntimeException to Exception so that it becomes a checked exception.

However after doing this, I'll have to add throws CustomException to all methods that will call this block of code. So just wondering if there's a more graceful way


Solution

  • You should use noRollbackFor attribute of @Transactional.

    @Transactional(noRollbackFor = customException.class)