Understanding Spring @Transactional Rollback Behavior and Exception Handling
This article demonstrates how Spring's @Transactional annotation rolls back transactions only for RuntimeException subclasses, shows practical MySQL update tests that trigger ArithmeticException, and explains how to configure rollback for checked exceptions using rollbackFor, with complete code examples.
First, a MySQL record is prepared for testing the update of the delflag field to 0:
UPDATE tbl_users set delflag='0' where account='admin'A simple test method annotated with @Transactional performs a division by zero, which throws java.lang.ArithmeticException (a subclass of RuntimeException), causing the transaction to roll back:
@Override
@Transactional
public Ret test() {
int i = articleMapper.test();
int a = 2/0; // throws ArithmeticException
if(i > 0){
ResultUtil.success();
}
return ResultUtil.error();
}Running this test shows that the database value is not changed because the transaction is rolled back when the RuntimeException occurs.
When the method catches the exception and rethrows a checked Exception, the transaction does not roll back, and the database update persists:
@Override
@Transactional
public Ret test() throws Exception {
int i = articleMapper.test();
try {
int a = 2/0;
} catch (Exception e) {
throw new Exception();
}
if(i > 0){
ResultUtil.success();
}
return ResultUtil.error();
}This demonstrates that @Transactional rolls back only for RuntimeException (and its subclasses). To roll back for checked exceptions like Exception, specify the rollbackFor attribute: @Transactional(rollbackFor = Exception.class) Therefore, when you need transaction rollback for any exception type, use @Transactional(rollbackFor = Exception.class) in your service methods.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
