Spring transaction: rollback by exception or throwable

I wonder if it is worth using instead

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)

use Throwable

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)

As I understand it, catching Errorwill help us to behave properly, even if something is really bad. Or maybe this will not help?

+8
source share
4 answers

As I understand it, detecting an error will help us to behave correctly, even if something really bad happens. Or maybe it will not help?

You do not need to explicitly specify rollbackFor = Throwable.class, because spring will roll back the transaction by default if it does Error.

See 12.5.3 Rollback of a declarative transaction.

Spring Framework , ; , RuntimeException. ( ). , , .

DefaultTransactionAttribute

public boolean rollbackOn(Throwable ex) {
    return (ex instanceof RuntimeException || ex instanceof Error);
}
+21

@Transactional, , Spring, Hibernate JDBC. JDBC , , SQLException JDBC SQLException.

@Transactional , .

,

@Transactional
public void persistAndWrite(Bean someBean) throws IOException {
    // DB operation
    getSession().save(someBean); 

    // File IO operation which throws IOException
    someFileService.writeToFile(someBean); 
}

, - .

@Transactional
public void persistAndThrowOutOfMemory(Bean someBean)  {
    // DB operation
    getSession().save(someBean);

    // consumes all memory, throws OutOfMemoryError
    someService.hugeOperationThrowsOutOfMemoryError(); 
}

, .

@Transactional . , .

+4

, , Throwable, Error - , . , . , , .

0

, , try{}catch{} , ,

catch {
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      }

try catch

, :

@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
0

Source: https://habr.com/ru/post/1658423/


All Articles