Why @Transactional Won’t Roll Back on Checked Exceptions and How to Fix It
This article demonstrates how Spring's @Transactional rolls back only RuntimeException subclasses, shows the failure to roll back a checked Exception, and explains how to use rollbackFor to ensure proper transaction rollback for all exception types.
Step 1: Prepare data in MySQL
Step 2: Simple test
Goal: set delflag to 0. SQL:
UPDATE tbl_users SET delflag='0' WHERE account='admin'Step 3: Test with @Transactional and a runtime exception
@Override
@Transactional
public Ret test() {
int i = articleMapper.test();
int a = 2/0; // throws ArithmeticException
if (i > 0) {
ResultUtil.success();
}
return ResultUtil.error();
}The division by zero throws java.lang.ArithmeticException, which extends RuntimeException. Spring rolls back the transaction, so the database value remains unchanged.
Step 4: Verify rollback
Step 5: Checked exception does not trigger rollback
@Override
@Transactional
public Ret test() throws Exception {
int i = articleMapper.test();
try {
int a = 2/0;
} catch (Exception e) {
throw new Exception(); // checked exception
}
if (i > 0) {
ResultUtil.success();
}
return ResultUtil.error();
}The caught exception is re‑thrown as java.lang.Exception (a checked exception). Spring does not roll back, and the database row is updated to 0.
Conclusion
@Transactional only rolls back RuntimeException and its subclasses. To roll back checked exceptions, specify @Transactional(rollbackFor = Exception.class). It is recommended to use this form for all insert, update, or delete operations.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
