Spring BootJava 21Spring Framework深入淺出

Spring Boot 05: database writes, commits, and rollback

··5 min read
Back to the Spring Boot learning path

An executed INSERT does not mean data will remain committed. This lesson inserts a first ticket, rejects a second, and queries again outside the transaction. The observation is commit or rollback, not merely whether an insert method ran.

Version note: this series is based on Spring Boot 3.5.16 because it targets JBoss EAP 8.1. Spring now offers the newer 4.1. For differences between 3.5 and 4.0, see the Spring Boot 4.0 Migration Guide in the sources.

Objects between the application and the database

text
TicketService → TicketStore → JdbcClient
                             → DataSource / connection pool → H2

Transaction proxy: begin → service work → commit / rollback

DataSource provides access to connections, while a pool manages reusable connections. JdbcClient supports parameterized SQL and result mapping. TicketStore holds this lab’s queries, and H2 is the database. Boot is not a database and does not make different SQL dialects automatically compatible.

java
// TicketStore.java
package com.keeponfirst.bootlab;

import java.util.Optional;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Repository;

@Repository
public class TicketStore {
    private final JdbcClient jdbc;

    public TicketStore(JdbcClient jdbc) { this.jdbc = jdbc; }

    public void insert(Ticket ticket) {
        jdbc.sql("INSERT INTO tickets (id, title) VALUES (:id, :title)")
            .param("id", ticket.id()).param("title", ticket.title()).update();
    }

    public Optional<Ticket> find(String id) {
        return jdbc.sql("SELECT id, title FROM tickets WHERE id = :id")
            .param("id", id)
            .query((rs, row) -> new Ticket(rs.getString("id"), rs.getString("title")))
            .optional();
    }
}

insert binds named parameters instead of concatenating input into SQL. find lists its columns and returns Optional, leaving missing-data policy to the service. There are no JPA entities, sessions, or lazy-loading rules here; passing this JDBC lab does not validate a Hibernate 4-to-6 migration.

The transaction surrounds the whole batch

java
// TicketService.java
package com.keeponfirst.bootlab;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class TicketService {
    private final TicketStore store;
    private final LabProperties properties;

    public TicketService(TicketStore store, LabProperties properties) {
        this.store = store;
        this.properties = properties;
    }

    public Ticket find(String id) {
        return store.find(id).orElseThrow(MissingTicket::new);
    }

    @Transactional
    public List<Ticket> createBatch(List<String> titles) {
        var created = new ArrayList<Ticket>();
        for (String raw : titles) {
            String title = raw == null ? "" : raw.trim();
            if (title.isBlank() || title.length() > properties.maxTitleLength()) {
                throw new BadTitle();
            }
            var ticket = new Ticket(UUID.randomUUID().toString(), title);
            store.insert(ticket);
            created.add(ticket);
        }
        return List.copyOf(created);
    }
}

createBatch is a public method on a managed service. An external invocation passes through its transaction proxy, covering the entire loop. A valid first title is inserted; a blank second one throws BadTitle. BadTitle extends RuntimeException. It triggers rollback under the default rules used here for database operations participating in the transaction.

public is not the only option. The Spring Framework 6.2 transaction page states: “As of 6.0, protected or package-visible methods can also be made transactional for class-based proxies by default.” The same paragraph notes that methods in interface-based proxies must still be public and declared in the interface.

Top: an external call from TicketController to createBatch passes the transaction proxy, which begins a transaction; the first row is inserted, the blank second title throws BadTitle, the proxy rolls back, and a query outside the transaction finds 0 rows. Bottom: a this.createBatch self-invocation bypasses the proxy, so no new transaction starts when the caller has none, and the first row may already be committed
Whether a call passes the transaction proxy decides whether a transaction exists. Rules from the Spring Framework 6.2 transaction docs; class names from the download. Diagram drawn by KeepOnFirst.

Sequential validation is essential to the experiment: one write must occur before a later failure. Production batches may prevalidate the entire input to avoid partial work. That is a different design; a test that never writes anything cannot establish rollback.

Trap: does an internal call activate transaction advice?

With default proxy-based transactions, a self-invocation such as this.createBatch(...) does not cross the proxy again. Without an existing transaction, the annotation on the internally called method will not start one through that path. Manual construction also bypasses the proxy. Clarify ownership and call flow before separating beans or using programmatic transactions.

The documented sentence is: “In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted.” The page then suggests AspectJ mode if self-invocations must also run in a transaction.

Swallowing an exception can make a method appear successful. Default rules roll back only for RuntimeException and Error; checked exceptions require checking rollback configuration, and projects may change global defaults. Do not assume every exception guarantees rollback.

Documented defaults: @Transactional with no attributes

SettingDefaultRelevance to this lab
PropagationPROPAGATION_REQUIREDJoins an existing transaction or starts one; the controller has none, so one starts
IsolationISOLATION_DEFAULTUses the database default; here, H2
Read/writeread-writeThe lab writes rows; no change needed
TimeoutUnderlying system default, or none if unsupportedNot set in this lab
RollbackRuntimeException or Error rolls back; checked Exception does notBadTitle extends RuntimeException, so it rolls back
@Transactional default settings (summarized from the Spring Framework 6.2 transaction docs)

The last row quotes: “Any RuntimeException or Error triggers rollback, and any checked Exception does not.” The rollback page also states that checked exceptions do not cause rollback in the default configuration.

Counterexample: make BadTitle a checked exception

java
// Variation for discussion only: not in the download, not executed.
public class BadTitle extends Exception { }

@Transactional(rollbackFor = BadTitle.class)
public List<Ticket> createBatch(List<String> titles) throws BadTitle {
    // same loop as above
}

The code above is the version with rollbackFor. Suppose BadTitle extends Exception and no rollback rule is set. Then, from the table above, the first row is committed with the transaction. The test counts 1 row, not 0. Adding rollbackFor = BadTitle.class restores 0 rows. The rollbackFor attribute name comes from the rollback page. That page shows only an XML example, rollback-for="NoProductInStockException", and no Java annotation example. This variation was not executed; trust your own mvn test result.

Exercise: inspect the result outside the transaction

java
@Test void aFailureAfterTheFirstInsertRollsBackEverything() {
    assertThatThrownBy(() -> service.createBatch(List.of("first", " ")))
        .isInstanceOf(BadTitle.class);
    assertThat(count()).isZero();
}

@Test void successfulBatchReallyCommits() {
    service.createBatch(List.of("first", "second"));
    assertThat(count()).isEqualTo(2);
}

These are excerpts from the test class, with its injection, cleanup, and count helper required. The tests deliberately omit @Transactional so the service owns the transaction. Each case clears the isolated H2 test table first. Run mvn test: the failing batch should leave zero rows and the successful batch two.

Answer: zero and two, then identify participating resources

In a disposable copy, remove @Transactional and rerun the test. The rollback case should fail because the first write may already be committed. Restore it afterwards. This checks whether the test detects a semantic change; removing the annotation is not a fix.

The evidence covers one H2 data source. MQ sends, remote APIs, and files do not automatically roll back simply because they occur in the annotated Java method. EAP/MDB work requires separately checking JTA, XA, the resource adapter, data source, and actual resource participation.

Download the complete ticket API lab (ZIP)Next: 06: Tests, debugging, deployment boundaries

Sources