Bird
Raised Fist0
Spring Bootframework~10 mins

Transaction management with @Transactional in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Transaction management with @Transactional
Start method call
Check for @Transactional
Yes
Open transaction
Execute method code
Method completes?
Commit
Close transaction
Return result
When a method with @Transactional is called, a transaction opens. If the method finishes without error, it commits. If an error occurs, it rolls back.
Execution Sample
Spring Boot
@Transactional
public void transferMoney() {
  debitAccount();
  creditAccount();
}
This method runs inside a transaction. If debit or credit fails, all changes undo.
Execution Table
StepActionTransaction StateMethod ExecutionResult
1Method transferMoney() calledNo transactionNot startedWaiting
2Detect @Transactional annotationNo transactionPreparing to startReady to open
3Open transactionTransaction openStart debitAccount()In progress
4Execute debitAccount()Transaction openDebit successfulContinue
5Execute creditAccount()Transaction openCredit successfulContinue
6Method completes normallyTransaction openAll steps doneCommit transaction
7Commit transactionTransaction committedEnd methodSuccess
8Return from methodNo transactionMethod finishedResult returned
💡 Method finishes without exceptions, so transaction commits and closes.
Variable Tracker
VariableStartAfter Step 3After Step 6Final
transactionStateNo transactionTransaction openTransaction openTransaction committed
methodExecutionNot startedIn progressAll steps doneFinished
Key Moments - 3 Insights
Why does the transaction rollback if an exception occurs inside the method?
Because in the execution_table, if the method does not complete normally (step 6), the transaction manager triggers a rollback instead of commit.
What happens if the method completes without errors?
As shown in step 6 and 7, the transaction commits and then closes, making all changes permanent.
Does the transaction start before or after the method code runs?
The transaction opens before the method code runs, as seen in step 3, ensuring all method actions are inside the transaction.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the transaction state at Step 4?
ANo transaction
BTransaction open
CTransaction committed
DTransaction rolled back
💡 Hint
Check the 'Transaction State' column at Step 4 in the execution_table.
At which step does the transaction commit?
AStep 7
BStep 6
CStep 5
DStep 8
💡 Hint
Look for the 'Commit transaction' action in the execution_table.
If debitAccount() throws an exception, what would happen to the transaction?
ATransaction stays open
BTransaction commits anyway
CTransaction rolls back
DTransaction closes without commit or rollback
💡 Hint
Recall that if the method does not complete normally, the transaction manager rolls back (see key_moments).
Concept Snapshot
@Transactional annotation wraps method in a transaction.
Transaction opens before method runs.
If method finishes normally, transaction commits.
If method throws exception, transaction rolls back.
Ensures all-or-nothing changes for data consistency.
Full Transcript
When you call a method marked with @Transactional, Spring opens a transaction before running the method code. Inside the method, all database changes happen within this transaction. If the method finishes without errors, Spring commits the transaction, making all changes permanent. But if an error happens, Spring rolls back the transaction, undoing all changes to keep data safe. This way, @Transactional helps keep your data consistent by making sure either all steps succeed or none do.

Practice

(1/5)
1. What is the main purpose of using @Transactional in a Spring Boot application?
easy
A. To ensure multiple database operations are executed as a single unit and rollback on failure
B. To speed up database queries by caching results
C. To automatically generate database schema from entities
D. To log all database queries for debugging

Solution

  1. Step 1: Understand the role of @Transactional

    @Transactional groups multiple database operations so they succeed or fail together.
  2. Step 2: Identify the effect on data consistency

    If any operation fails, all changes are rolled back to keep data correct.
  3. Final Answer:

    To ensure multiple database operations are executed as a single unit and rollback on failure -> Option A
  4. Quick Check:

    @Transactional = atomic database actions [OK]
Hint: Think: all-or-nothing for database changes [OK]
Common Mistakes:
  • Confusing @Transactional with caching or logging
  • Thinking it speeds up queries
  • Assuming it auto-generates schema
2. Which of the following is the correct way to apply @Transactional to a method in a Spring Boot service class?
easy
A. @Transactional public void updateData() { ... }
B. public @Transactional void updateData() { ... }
C. public void updateData() @Transactional { ... }
D. public void updateData() { @Transactional ... }

Solution

  1. Step 1: Recall correct annotation placement

    Annotations like @Transactional go before the method signature.
  2. Step 2: Check each option's syntax

    @Transactional public void updateData() { ... } places @Transactional correctly before the method declaration.
  3. Final Answer:

    @Transactional public void updateData() { ... } -> Option A
  4. Quick Check:

    Annotation before method = correct syntax [OK]
Hint: Annotations always go before method signature [OK]
Common Mistakes:
  • Placing annotation inside method body
  • Putting annotation after method signature
  • Using annotation as a modifier keyword
3. Consider this Spring Boot service method annotated with @Transactional:
@Transactional
public void saveUserAndAccount(User user, Account account) {
    userRepository.save(user);
    accountRepository.save(account);
    if(account.getBalance() < 0) {
        throw new RuntimeException("Negative balance not allowed");
    }
}
What happens if account.getBalance() < 0 is true during execution?
medium
A. An error is logged but changes are committed
B. Only the user is saved, account save is rolled back
C. Both user and account are saved to the database
D. Neither user nor account is saved; transaction rolls back

Solution

  1. Step 1: Understand rollback behavior of @Transactional

    By default, RuntimeExceptions cause the transaction to rollback all changes.
  2. Step 2: Analyze the exception thrown

    The method throws RuntimeException if balance is negative, triggering rollback.
  3. Final Answer:

    Neither user nor account is saved; transaction rolls back -> Option D
  4. Quick Check:

    RuntimeException triggers rollback = no data saved [OK]
Hint: Exception inside @Transactional rolls back all changes [OK]
Common Mistakes:
  • Assuming partial saves happen
  • Thinking only last save rolls back
  • Ignoring exception effect on transaction
4. Given this method in a Spring Boot service:
@Transactional
public void updateRecords() {
    recordRepository.updateA();
    recordRepository.updateB();
    // Missing exception handling
}
If updateB() throws a checked exception (not RuntimeException), what will happen to the transaction?
medium
A. Transaction will rollback automatically
B. Transaction will commit despite the exception
C. Transaction will rollback only if exception is caught and rethrown as RuntimeException
D. Transaction will pause until exception is handled

Solution

  1. Step 1: Recall default rollback rules of @Transactional

    By default, only unchecked exceptions (RuntimeException) cause rollback.
  2. Step 2: Analyze checked exception behavior

    Checked exceptions do not trigger rollback unless configured or rethrown as RuntimeException.
  3. Final Answer:

    Transaction will commit despite the exception -> Option B
  4. Quick Check:

    Checked exceptions do not rollback by default [OK]
Hint: Only RuntimeExceptions rollback by default [OK]
Common Mistakes:
  • Assuming all exceptions cause rollback
  • Not knowing difference between checked and unchecked exceptions
  • Expecting rollback without configuration
5. You have a Spring Boot service with two methods:
public void outerMethod() {
    innerMethod();
}

@Transactional
public void innerMethod() {
    // database updates
    if(someCondition) throw new RuntimeException();
}
If outerMethod() is called, will the transaction rollback if innerMethod() throws the exception? Assume default proxy-based Spring transaction management.
hard
A. Yes, but only if outerMethod is also annotated with @Transactional
B. Yes, transaction rolls back because innerMethod is @Transactional
C. No, transaction does not rollback because outerMethod is not @Transactional and calls innerMethod internally
D. No, because RuntimeException does not trigger rollback in this case

Solution

  1. Step 1: Understand Spring proxy behavior for @Transactional

    Spring uses proxies, so self-invocation (method calling another in same class) bypasses proxy and ignores @Transactional.
  2. Step 2: Analyze effect on transaction rollback

    Since outerMethod calls innerMethod directly, @Transactional on innerMethod is ignored, so no transaction starts and no rollback occurs.
  3. Final Answer:

    No, transaction does not rollback because outerMethod is not @Transactional and calls innerMethod internally -> Option C
  4. Quick Check:

    Self-call bypasses @Transactional proxy = no rollback [OK]
Hint: Self-calls ignore @Transactional proxy, no transaction started [OK]
Common Mistakes:
  • Assuming @Transactional always works on internal calls
  • Thinking RuntimeException always triggers rollback here
  • Not knowing Spring proxy limitations