Mastering Spring @Transactional: Exception Types and Rollback Strategies
This guide explains Java exception classification, the default rollback behavior of Spring's @Transactional annotation, and how to configure rollback for checked and unchecked exceptions while offering best‑practice recommendations for transactional method design.
Exception Classification
In Java, exceptions are divided into checked exceptions (subclasses of Exception excluding RuntimeException) and unchecked exceptions, which include RuntimeException and its subclasses as well as Error.
Unchecked exceptions cause the thread or the main program to terminate if not handled; therefore they should be caught to prevent thread abort, discarding the problematic data and logging the error.
Checked exceptions: all Exception subclasses except RuntimeException.
Unchecked exceptions: RuntimeException and its subclasses, plus Error.
If a runtime exception is not handled, the thread may abort or the main program may terminate.
For non‑runtime (checked) exceptions such as IOException, SQLException, or custom exceptions, the Java compiler forces you to catch them; otherwise the code will not compile.
@Transactional Usage
Spring's transaction infrastructure rolls back by default only for runtime and unchecked exceptions. Checked exceptions do not trigger a rollback unless explicitly configured.
Make checked exceptions roll back: @Transactional(rollbackFor=Exception.class) Prevent unchecked exceptions from rolling back: @Transactional(notRollbackFor=RuntimeException.class) Method that does not need a transaction (read‑only): @Transactional(propagation=Propagation.NOT_SUPPORTED) Note: If an exception is caught inside the method, the transaction will not roll back; re‑throw the exception after catching to ensure rollback.
Summary
Spring recommends applying @Transactional on concrete classes or methods rather than on interfaces, unless you are using interface‑based proxies. Keep transactional methods simple: perform ordinary read‑only queries outside the transaction and reserve the transaction for insert, update, delete, and locking queries.
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.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
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.
