Transactions & database migrations (Flyway)
Use @Transactional correctly and version your schema.
By Invicly Tech, , in Backend Java Development. About 12 minutes to read.
In short
@Transactional makes a method all-or-nothing: either every database change commits, or all are rolled back. Flyway versions your schema with numbered SQL files applied in order at startup.
Explained simply
A transaction is a group of database changes that must succeed or fail together. Moving money is the classic case: take 100 from account A and add 100 to account B. If the second step fails, the first must be undone, or money disappears. The database can do this for you, but someone has to say where the group starts and ends.
In Spring you say it with one annotation: @Transactional on a service method. Spring opens a transaction before the method runs. If the method returns normally, it commits (saves everything). If it throws an unchecked exception, it rolls back (undoes everything). You write normal code and Spring handles the begin, commit and rollback.
The second half of this topic is the shape of the database itself: tables, columns and indexes. That shape is called the schema, and it changes as your app grows. Flyway keeps those changes as numbered SQL files in your project, such as V1__create_users.sql and V2__add_email.sql, and applies the missing ones every time the app starts.
Together they give you two safety nets. Transactions keep the data consistent while the app runs. Migrations keep the schema the same on every laptop, test server and production database, and give you a written history of every change.
Press Play on a diagram to walk through it one step at a time.
- Caller to Spring proxy: transfer(1, 2, 100)1transfer(1, 2, 100)
- Spring proxy to Database: BEGIN2BEGIN
- Spring proxy to Your service: call real method3call real method
- Your service to Database: UPDATE debit, UPDATE credit4UPDATE debit, UPDATE credit
- Your service to Spring proxy: returns or throws5returns or throws
- Spring proxy to Database: COMMIT, or ROLLBACK on exception6COMMIT, or ROLLBACK on exception
- Spring proxy to Caller: result7result
- 1App starts
Flyway runs before JPA uses the schema
- 2Read history table
flyway_schema_history lists applied versions
- 3Find pending files
V3__add_index.sql not yet applied
- 4Apply in order
Each migration runs once, by version number
- 5Record checksum
Edited old files are detected and rejected
- OrderService (outer) to Transaction manager: Begin transaction (REQUIRED)1Begin transaction (REQUIRED)
- OrderService (outer) to StockService (inner): reserve(): joins the same transaction2reserve(): joins the same transaction
- StockService (inner) to Transaction manager: Throws: mark rollback-only3Throws: mark rollback-only
- StockService (inner) to OrderService (outer): Exception caught, outer carries on4Exception caught, outer carries on
- OrderService (outer) to Transaction manager: Method returns: try to commit5Method returns: try to commit
- Transaction manager to OrderService (outer): Rolls back, throws UnexpectedRollbackException6Rolls back, throws UnexpectedRollbackException
In depth
The proxy: why some @Transactional methods do nothing
Spring does not change your class. At startup it wraps the bean in a proxy, a small object with the same methods. Other beans get the proxy injected. When they call a method, the proxy asks the transaction manager to begin, calls your real method, then commits or rolls back.
That design explains the classic traps. A call from one method to another inside the same class uses this, not the proxy, so the inner annotation is ignored. Private methods can never be intercepted. A bean you create yourself with new is not a Spring bean, so it has no proxy at all. The fix is usually to move the method to a second bean, or to put @Transactional on the public entry method that the controller calls.
- Put @Transactional on service methods, not on controllers or repositories you write
- Self-invocation skips the proxy: this.other() runs with no new transaction rules
- Log org.springframework.transaction at DEBUG to see begin, commit and rollback
Propagation: joining or starting a transaction
Propagation decides what happens when a transactional method is called while a transaction is already running. The default, REQUIRED, joins the existing one or starts a new one if there is none. Most of your code should use it.
REQUIRES_NEW suspends the outer transaction and starts a completely separate one, with its own database connection. It commits or rolls back on its own, which is useful for audit logs that must be saved even when the main work fails. Use it with care: each nested call holds a second connection from the pool, so heavy use can exhaust the pool. NESTED creates a savepoint inside the same transaction, so a failure can roll back to that point without losing the earlier work; it needs a JDBC-based transaction manager that supports savepoints. MANDATORY throws if no transaction exists, a good guard for methods that must never run alone.
- Joins the caller's transaction
- One connection, one commit
- Inner failure fails everything
- Right choice for most code
- Suspends the caller's transaction
- Second connection from the pool
- Commits even if the caller rolls back
- Good for audit and outbox rows
- Same transaction, adds a savepoint
- Rolls back only to the savepoint
- Outer rollback still undoes it
- Needs savepoint support (JDBC)
Rollback rules and the rollback-only surprise
By default Spring rolls back on RuntimeException and Error, and commits on checked exceptions such as IOException. The idea comes from old EJB rules: a checked exception was seen as an expected business outcome. Change it per method with rollbackFor = Exception.class, or keep a specific runtime exception from rolling back with noRollbackFor.
A common surprise: an inner REQUIRED method throws, the outer method catches the exception and carries on. Because both share one transaction, the inner failure already marked it rollback-only. When the outer method returns, Spring tries to commit, finds the mark, rolls back and throws UnexpectedRollbackException. If the inner work is allowed to fail on its own, it needs REQUIRES_NEW or NESTED, not a try/catch.
- @Transactional(rollbackFor = Exception.class) also rolls back on checked exceptions
- readOnly = true lets Hibernate skip dirty checking and flushing for queries
- timeout = 5 rolls back if the transaction runs longer than 5 seconds
How Flyway names, orders and checks migrations
Spring Boot runs Flyway automatically when flyway-core is on the classpath, before JPA starts. Files live in classpath:db/migration by default. A versioned file is named V, a version, two underscores, then a description: V3__add_order_index.sql. Versions sort numerically, so V10 runs after V9. Repeatable files start with R__ and rerun whenever their content changes, handy for views and functions.
Flyway stores each applied version and a checksum in the flyway_schema_history table. On the next start it validates: if an applied file was edited, the checksum differs and startup fails. That is a feature, it stops two databases from quietly drifting apart. For an existing database with no history table, set spring.flyway.baseline-on-migrate=true once. Since Flyway 10, PostgreSQL support lives in a separate module, flyway-database-postgresql, which you add next to flyway-core.
- spring.flyway.locations=classpath:db/migration is the default location
- Use spring.jpa.hibernate.ddl-auto=validate so Hibernate checks but never changes the schema
- Undo migrations are not in the free edition: write a new forward migration instead
Changing a live schema without downtime
During a rolling deploy, old and new versions of the app run at the same time against one database. A migration that renames or drops a column breaks the old version instantly. The safe method is called expand and contract.
First expand: add the new column or table, nullable, so old code ignores it. Deploy code that writes to both old and new places. Backfill old rows in batches so you do not lock a large table for minutes. Switch reads to the new column. Only after no running version uses the old column do you contract with a final migration that drops it. In PostgreSQL, create indexes on big tables with CREATE INDEX CONCURRENTLY, which cannot run inside a transaction, so put it in its own migration file and turn off the transaction for that script.
- 1Add new column
Nullable, so old code keeps working
- 2Write to both
New release fills old and new columns
- 3Backfill in batches
Copy old rows a few thousand at a time
- 4Read from new
Next release uses only the new column
- 5Drop old column
Final migration, once nothing reads it
Learn it in 3 short steps
About 1h each. Track them with a timer in your plan.
- 1Use @Transactional and propagation~1h
- 2Understand rollback rules~1h
- 3Version the schema with Flyway migrations~1h
Key points
- By default, rollback happens for unchecked exceptions, not checked ones; use rollbackFor to change that.
- Calling a @Transactional method from the same class skips the proxy, so no transaction starts.
- Default propagation REQUIRED joins an existing transaction or starts a new one.
- Never edit an applied Flyway migration; add a new versioned file instead.
Key terms
Tap a card to flip it. 0/5 known
Examples
@Service
class TransferService {
private final AccountRepository accounts;
TransferService(AccountRepository accounts) { this.accounts = accounts; }
@Transactional
public void transfer(long from, long to, BigDecimal amount) {
accounts.debit(from, amount);
accounts.credit(to, amount); // if this throws, the debit is rolled back
}
}
// src/main/resources/db/migration/V2__add_email.sql
// ALTER TABLE users ADD COLUMN email TEXT;An audit row that survives a failed order
Every order attempt must be audited, even when the order fails. Step 1: put the audit write in its own bean, so the call goes through a proxy. Step 2: mark it REQUIRES_NEW, so it commits in its own transaction. Step 3: call it from placeOrder. If chargeCard throws, the order rows roll back, but the audit row is already committed. Keep the audit method short, because while it runs the outer transaction holds its connection too.
@Service
class AuditService {
private final AuditRepository audits;
AuditService(AuditRepository audits) { this.audits = audits; }
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(String event) { audits.save(new AuditEntry(event, Instant.now())); }
}
@Transactional
public void placeOrder(Order o) {
audit.record("order attempt " + o.getRef()); // commits on its own
orders.save(o);
payments.chargeCard(o); // throws: order rolls back, audit stays
}Adding a required column to a big table
You need users.country to be NOT NULL, and the table has 20 million rows. Doing it in one ALTER with a default is fine in modern PostgreSQL (11 and later store a constant default without rewriting the table), but a computed value needs a backfill. Step 1: V7 adds the column as nullable. Step 2: V8 fills it. Step 3: V9 adds the NOT NULL rule once every row has a value. Each file is applied once and recorded in flyway_schema_history.
-- V7__add_user_country.sql
ALTER TABLE users ADD COLUMN country TEXT;
-- V8__backfill_user_country.sql
UPDATE users u SET country = a.country
FROM addresses a
WHERE a.user_id = u.id AND u.country IS NULL;
UPDATE users SET country = 'unknown' WHERE country IS NULL;
-- V9__user_country_not_null.sql
ALTER TABLE users ALTER COLUMN country SET NOT NULL;Quick reference
- @Transactional rolls back on RuntimeException and Error, not on checked exceptions
- rollbackFor = Exception.class makes checked exceptions roll back too
- Self-invocation and private methods bypass the proxy: no transaction rules apply
- REQUIRES_NEW uses a second connection; NESTED uses a savepoint in the same one
- Flyway file name: V2__add_email.sql (V, version, two underscores, description) in db/migration
- Never edit an applied migration; its checksum is validated on every start
- Pair Flyway with spring.jpa.hibernate.ddl-auto=validate
- Keep transactions short: no HTTP calls or slow work while a connection is held
Common mistakes
- Putting @Transactional on a private method or self-invoked method, where it has no effect.
- Expecting a checked exception to trigger rollback by default.
- Letting Hibernate ddl-auto change production schemas instead of migrations.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Make a service method roll back when it throws a checked BusinessException, and prove it with a test that checks the row count.
- Exercise 2medium
You have a private @Transactional helper called from a public method in the same class, and it never rolls back. Fix it two different ways.
- Exercise 3hard
Add an index to a 50-million-row orders table in PostgreSQL through Flyway without blocking writes.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should @Transactional go on the class or on each method?
- Either works; on the class it applies to every public method. Many teams put readOnly = true on the class and override with a plain @Transactional on the methods that write.
- Do I need @Transactional on Spring Data repository methods?
- Not for the methods inherited from JpaRepository: they are already transactional, with save in a write transaction and findById or findAll read-only. You add it on your service to group several calls into one transaction.
- Flyway or Liquibase?
- Both version your schema well. Flyway uses plain SQL files and is simpler to learn; Liquibase adds XML, YAML or JSON changelogs and more built-in rollback features.
- Can Flyway roll back a migration?
- The free edition has no undo command. The usual practice is to write a new forward migration that reverses the change, and to back up before risky releases.