Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 34

    Transactions

    @Transactional wraps a method in a database transaction: all writes commit together or roll back together.

    Course progress0%
    Focus
    3 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    @Transactional wraps a method in a database transaction: all writes commit together or roll back together. It's the single most important annotation for data correctness.

    Understanding the topic

    The rules nobody tells you:

    • @Transactional works via Spring proxies — calling a transactional method from the same class bypasses it.
    • Default rollback only on RuntimeException; checked exceptions don't roll back unless you say so.
    • readOnly = true hints the DB and skips dirty checking — big perf win for queries.
    • propagation = REQUIRES_NEW opens an independent TX — used for audit logs that must commit even on failure.

    Informative example

    ts
    @Service
    @Transactional // class-level default for all methods
    public class TransferService {
    @Transactional(readOnly = true)
    public Account get(Long id) { ... }
    @Transactional(rollbackFor = Exception.class)
    public void transfer(Long from, Long to, int amount) {
    var src = repo.findByIdForUpdate(from); // pessimistic lock
    var dst = repo.findByIdForUpdate(to);
    src.debit(amount);
    dst.credit(amount);
    }
    }
    Ready to mark this lesson complete?Track your journey across the entire course.