Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 30

Atomic Transactions with @Transactional

This lesson is built with resources from youtube.com, marcobehler.com and 1 more site.

Hello! Welcome to your next lesson.

In our previous session, we built a robust global exception handler using @ControllerAdvice. This ensures our API provides clean, predictable error responses to clients. We ended with a crucial question: what happens if a business operation involves multiple database writes, and one fails midway? This could leave our data in an inconsistent state.

Today, we'll tackle that exact problem. This lesson addresses the learning outcome: Use the @Transactional annotation on service methods to ensure data consistency and demonstrate an automatic rollback. We'll learn how to group multiple database operations into a single, atomic "unit of work" that either succeeds completely or fails completely, leaving the database untouched.

Transactions: The "All or Nothing" Principle

In database systems, a transaction is a sequence of operations performed as a single logical unit. The core idea is that all operations within the transaction must succeed. If even one fails, the entire set of operations is undone or "rolled back," as if it never happened. This guarantees data integrity.

MERN vs. Spring Boot: Declarative Transactions

In your experience with Node.js and a database like MongoDB, you might have managed transactions imperatively. This often involves manually starting a session, wrapping your database calls in a try...catch block, and explicitly calling commitTransaction() on success or abortTransaction() on failure.

// A conceptual MERN transaction
const session = await db.startSession();
session.startTransaction();
try {
  // Step 1: Create a post
  await Post.create([{ ... }], { session });

  // Step 2: Update the user's post count (this might fail)
  await User.updateOne({ _id: userId }, { $inc: { postCount: 1 } }, { session });

  // If both succeed, commit the transaction
  await session.commitTransaction();
} catch (error) {
  // If anything fails, abort the entire transaction
  await session.abortTransaction();
  throw error;
} finally {
  session.endSession();
}

Spring Boot, with the help of Spring Data JPA, offers a much more elegant, declarative approach with the @Transactional annotation. Instead of writing the boilerplate try/catch/commit/rollback logic, you simply declare that a method should be transactional, and Spring handles the rest behind the scenes.


The Problem: Data Inconsistency in Action

Let's first understand the problem we're trying to solve. Imagine a service method that needs to perform two database updates. If the second one fails, what happens to the first one?

This short video explains this classic problem using a bank transfer analogy.

How Spring @Transactional Works Internally ? ( AOP, Proxies & Debug Walkthrough) @Javatechie

To see why transactions are essential, let's watch this clip from the 'How Spring @Transactional Works Internally' video by Java Techie. It clearly illustrates how a multi-step database operation can lead to data inconsistency without proper transaction management.

Please watch from 01:32 to 03:19. Focus on the scenario where deducting money from the sender's account succeeds, but crediting the receiver's account fails, leaving the system in an inconsistent state.

As the video shows, without a transaction, a partial success is a total failure for data integrity.


Hands-On: Demonstrating Automatic Rollback

Let's apply this to our blog platform. We'll create a scenario where we try to save two posts in one operation, but the second one is designed to fail a database constraint.

Step 1: The Scenario (Without @Transactional)

First, let's see what happens without any transaction management.

  1. In your PostService.java, add a new method called createPostsWithFailure.

    // In PostService.java
    
    public void createPostsWithFailure() {
        // This post is valid and should save successfully
        PostDTO validPost = new PostDTO(null, "Valid Title", "This is a valid post.", null, null, null);
        createPost(validPost);
    
        // This post has a title that is too long, violating the DB constraint (VARCHAR(255))
        // or a validation constraint (@Size) if you have one.
        PostDTO invalidPost = new PostDTO(null, "This title is intentionally made very very long to fail the database constraint we have set on our Post entity's title field. This will cause an exception to be thrown during the persistence operation.", "Content doesn't matter here.", null, null, null);
        createPost(invalidPost);
    }
    

    Note: If your Post entity's title field has a @Size constraint, this will also trigger a ConstraintViolationException which will be wrapped in another exception by the time it reaches the service layer from the repository.

  2. To easily test this, let's create a temporary CommandLineRunner that calls this method on startup. Create a new file TransactionRunner.java in your main package.

    package com.example.blogplatform;
    
    import com.example.blogplatform.post.PostService;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class TransactionRunner implements CommandLineRunner {
    
        private static final Logger logger = LoggerFactory.getLogger(TransactionRunner.class);
        private final PostService postService;
    
        public TransactionRunner(PostService postService) {
            this.postService = postService;
        }
    
        @Override
        public void run(String... args) throws Exception {
            logger.info("Number of posts before test: {}", postService.getAllPosts(0, 5).getTotalElements());
            try {
                postService.createPostsWithFailure();
            } catch (Exception e) {
                logger.error("Expected exception caught: {}", e.getMessage());
            }
            logger.info("Number of posts after test: {}", postService.getAllPosts(0, 5).getTotalElements());
        }
    }
    
  3. Run the application. Clear your database table posts before you run it for a clean test. Observe the logs. You should see something like this:

    Number of posts before test: 0
    Expected exception caught: ... DataException: value too long for type character varying(255) ...
    Number of posts after test: 1
    

    The "Valid Title" post was committed to the database, but the second one failed. Our database is now in an inconsistent state relative to the business operation we tried to perform.

Step 2: The Solution (With @Transactional)

Now, let's add one simple annotation to fix this.

  1. Go back to PostService.java and add @Transactional to the createPostsWithFailure method.

    // In PostService.java
    import org.springframework.transaction.annotation.Transactional;
    
    // ...
    
    @Transactional
    public void createPostsWithFailure() {
        // ... method body remains the same
    }
    
  2. Clear your database and run the application again. Now, look at the logs:

    Number of posts before test: 0
    Expected exception caught: ... DataException: value too long for type character varying(255) ...
    Number of posts after test: 0
    

    Success! The exception was still thrown, but @Transactional intercepted it and triggered a rollback. The "Valid Title" post, which was inserted during the method execution, was removed from the database transaction. The entire operation was treated as a single atomic unit.

For a comprehensive walkthrough of a similar example, you can refer to the official Spring guide on "Managing Transactions". The code in sections "Create a Booking Service", "There is also a CommandLineRunner...", and the output section clearly demonstrate this rollback behavior.


How Does @Transactional Work Internally?

The "magic" behind @Transactional is a core Spring concept: Aspect-Oriented Programming (AOP) and dynamic proxies. This is fundamental to understanding Spring and is a common interview topic.

Let's start with a high-level guide that explains the mechanics.

Spring Transaction Management: @Transactional In-Depth

The article 'Spring Transaction Management: @Transactional In-Depth' by Marco Behler is an excellent resource for understanding the fundamentals. It demystifies the annotation by first explaining the raw JDBC calls that Spring abstracts away.

Please read the following sections: 'How plain JDBC Transaction Management works': This shows the low-level Java code (connection.setAutoCommit(false), connection.commit(), connection.rollback()) that @Transactional manages for you. 'How to use Spring’s @Transactional annotation': This introduces the annotation itself. 'CGlib & JDK Proxies - @Transactional under the covers': This is the most critical part. It explains how Spring creates a proxy object that wraps your service to manage the transaction. Pay close attention to the diagram showing the UserRestController talking to a proxy, not the real UserService. 'For what do you need a Transaction Manager': This explains the role of PlatformTransactionManager in orchestrating the transaction.

Spring Declarative Transaction Management Flow
This diagram from the Spring documentation illustrates the proxy pattern. Your code (Caller) thinks it's calling the target method directly, but it's actually invoking an AOP Proxy. This proxy, via a 'Transaction Advisor', begins the transaction, calls the real target method, and then commits or rolls back based on the outcome.

Debugging the Transaction Flow

Reading about proxies is one thing; seeing them in action is another. Your "debugging-first" preference is perfect for this. Let's step through the code and see the proxy mechanism live.

This video provides an outstanding walkthrough of debugging into the Spring framework's transaction management code.

How Spring @Transactional Works Internally ? ( AOP, Proxies & Debug Walkthrough) @Javatechie

The 'How Spring @Transactional Works Internally' video by Java Techie has a fantastic live debugging session that peels back the layers of abstraction.

Please watch from 04:16 to 15:55, and then the failure scenario from 29:08 to 32:56. The Theory (04:16 - 07:17): First, the video explains that @Transactional uses AOP's 'around advice' to wrap your method call. The Proxy (07:17 - 15:55): It then explains how Spring creates a CGLIB proxy class that intercepts the method call and delegates the transaction handling to a TransactionInterceptor. The Rollback (29:08 - 32:56): This part debugs a failure scenario, showing exactly how the catch block in Spring's internal code is triggered, leading to a rollback.

Your Debugging Task:

  1. Place a breakpoint on the first line inside your @Transactional createPostsWithFailure() method in PostService.

  2. Run the application in Debug Mode. The execution will pause at your breakpoint.

  3. Look at the call stack view in your IDE (usually in the Debug panel). You will not see your TransactionRunner calling PostService directly. Instead, you'll see a stack trace that looks something like this:

    createPostsWithFailure:123, PostService
    invoke:-1, CGLIB$AOP_PROXY ...
    invokeJoinpoint:749, JdkDynamicAopProxy
    invoke:208, TransactionInterceptor // <-- The magic happens here!
    ...
    run:25, TransactionRunner
    ...
    

    Note: The exact class names might differ slightly.

    That TransactionInterceptor and the CGLIB proxy class are the concrete evidence of the AOP proxy at work. You are not inside the original PostService object, but a dynamically generated wrapper that has already started a transaction.


A Critical Pitfall: Internal Method Calls

Because @Transactional relies on external calls being intercepted by a proxy, it has one major "gotcha" that catches many developers.

If a non-transactional method within the same class calls a transactional method, the transaction logic will not be applied.

@Service
public class MyService {

    public void methodA() {
        // ... some logic
        this.methodB(); // THIS CALL WILL NOT BE TRANSACTIONAL
    }

    @Transactional
    public void methodB() {
        // ... database logic
    }
}

Why? Because the call to this.methodB() is an internal Java method call. It doesn't go through the proxy that wraps the MyService bean. The proxy only intercepts calls that come from other beans. The article from Marco Behler you read earlier explains this perfectly in the section "The most common @Transactional pitfall".


Conclusion

In this lesson, we demystified one of Spring's most powerful features. You have learned not just how to use @Transactional, but why it's necessary and how it works under the hood.

Key Takeaways:

  • Transactions ensure atomicity, meaning a multi-step operation is "all or nothing," which prevents data inconsistency.
  • The @Transactional annotation is a declarative way to apply transaction management to a service method.
  • By default, @Transactional rolls back operations when a RuntimeException (an unchecked exception) is thrown.
  • The underlying mechanism is AOP and dynamic proxies. Spring wraps your service bean in a proxy that intercepts method calls to begin, commit, or roll back transactions.
  • The PlatformTransactionManager is the component that handles the low-level JDBC connections.
  • Be aware that internal method calls within the same bean bypass the transactional proxy.

Preview of the Next Lesson:

Our API is now more robust, with validation, error handling, and transactional data operations. However, when things go wrong in a production environment, we need clear visibility into what the application was doing. In the next lesson, "Configure structured JSON logging for the application using Logback to trace request flows," we will move beyond simple console logs to create structured, machine-readable logs that are essential for modern monitoring and analysis.