1. Concept library
  2. Java & Spring Boot
  3. Module 8: Data access with JPA

Concept

Transactions

@Transactional runs a method inside one database transaction, committing at the end and rolling back on an unchecked exception. Service methods that change several rows need it so partial updates never persist.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what @Transactional guarantees and when it rolls back
  2. Write a service method that changes several rows in one transaction
  3. Spot the self-invocation that bypasses the proxy

In practice

A few lines that show Transactions doing its job.

Java
@Service
public class TransferService {
    @Transactional
    public void transfer(UUID from, UUID to, long cents) {
        var source = accounts.findById(from).orElseThrow();
        var target = accounts.findById(to).orElseThrow();
        source.withdraw(cents);     // throws -> whole transaction rolls back
        target.deposit(cents);
    }
}

The common mistake

Watch for

Calling a @Transactional method from another method of the same class. The call bypasses the proxy, so no transaction starts. Put the transactional method on a bean that is called from outside.

What to know first

Your roadmap puts these before Transactions, unless you already know them.

How it stays learned

Once a session shows you understand Transactions, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Transactions.

Previous in the module← Relationships