@Transactional(rollbackFor = MyCheckedException.class) public void foo() { throw new RuntimeException(); }
Will this transaction get rolled back, or do I need to include RuntimeException.class in the annotation as well?
rollbackFor = Exception.class -> means if 'Exception.class' or any other which extends this class will be thrown during transaction, whole transaction will be rollbacked. Without any changes made.
@Transactional only rolls back transactions for unchecked exceptions. For checked exceptions and their subclasses, it commits data. So although an exception is raised here, because it's a checked exception, Spring ignores it and commits the data to the database, making the system inconsistent.
The default @Transactional settings are: The propagation setting is PROPAGATION_REQUIRED. The isolation level is ISOLATION_DEFAULT. The transaction is read/write.
Annotation Type Transactional. Describes a transaction attribute on an individual method or on a class. When this annotation is declared at the class level, it applies as a default to all methods of the declaring class and its subclasses.
No need to include RuntimeException
in rollbackFor
list. It will handle that even if you do not mention it.
I've tried it out for jdbcTemplate:-
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = MyException.class) public void updateSalary(final int increment){ jdbcTemplate.update("update EMPLOYEE set emp_salary = emp_salary + ?", increment); throw new RuntimeException("update exception"); }
Output: After Insertion: 1 Deepak 35000 2 Yogesh 35000 3 Aditya 35000 update exception After Update 1 Deepak 35000 2 Yogesh 35000 3 Aditya 35000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With