Chapter 10

Transactions and session management

A SqlSession is a connection, a transaction and a cache bundled together. Almost every MyBatis production incident traces back to one of those three being held for the wrong length of time.

⏱ 18 min readLevel: intermediate
Sequence diagram of a service method opening a session, executing statements through the executor, committing and closing
Who opens, who commits, who closes — and where Spring takes over.

The openSession variants

SqlSessionFactory API
SqlSession openSession();                                   // autoCommit = false
SqlSession openSession(boolean autoCommit);
SqlSession openSession(Connection connection);              // bring your own connection
SqlSession openSession(TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType);
SqlSession openSession(ExecutorType execType, boolean autoCommit);
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
SqlSession openSession(ExecutorType execType, Connection connection);
The no-argument version does not autocommit

openSession() starts a transaction. Every write is lost unless you call commit(). This is the single most common first-day MyBatis bug: the insert logs happily, the row is never there.

The canonical pattern

OrderService.java — no Spring
public void placeOrder(Order order, List<OrderLine> lines) {

    try (SqlSession session = factory.openSession()) {   // tx begins
        OrderMapper  orders  = session.getMapper(OrderMapper.class);
        StockMapper  stock   = session.getMapper(StockMapper.class);

        orders.insert(order);
        for (OrderLine line : lines) {
            line.setOrderId(order.getId());
            orders.insertLine(line);

            if (stock.decrement(line.getProductId(), line.getQuantity()) == 0) {
                throw new OutOfStockException(line.getProductId());
            }
        }
        session.commit();                                 // tx ends
    }                                                     // close(): rolls back if not committed
}

close() rolls back any uncommitted work, so the exception path needs no explicit rollback() call. Being explicit does no harm and reads clearly, but it is not required.

Scope rules, stated plainly

ObjectScopeThread-safeRule
SqlSessionFactoryBuildermethod—Discard after build()
SqlSessionFactoryapplicationYesCreate once, never close
SqlSessionrequest / methodNotry-with-resources, never a field
MappermethodNoTied to its session; do not cache
Never store a SqlSession in a field

A session held in a servlet, singleton or static field will be used by many threads at once. Symptoms are spectacular and non-deterministic: interleaved result sets, phantom commits, ClassCastException from the shared cache. In Spring, inject the mapper interface and let SqlSessionTemplate handle the session per thread.

Autocommit

two behaviours
// each statement commits by itself — no rollback possible
try (SqlSession session = factory.openSession(true)) {
    session.getMapper(AuditMapper.class).log(event);
}

// grouped: all or nothing
try (SqlSession session = factory.openSession(false)) {
    // ...
    session.commit();
}

Autocommit is right for genuinely independent writes — audit rows, metrics, fire-and-forget logs. It is wrong for anything that must be consistent with something else.

Isolation levels

setting the level
try (SqlSession session = factory.openSession(
        TransactionIsolationLevel.REPEATABLE_READ)) {
    // ...
}
LevelPreventsStill allows
READ_UNCOMMITTEDnothingdirty reads
READ_COMMITTEDdirty readsnon-repeatable reads, phantoms
REPEATABLE_READ+ non-repeatable readsphantoms (except in InnoDB)
SERIALIZABLEeverything— at a real throughput cost
NONEuses the driver default—

Defaults differ: PostgreSQL and Oracle use READ_COMMITTED, MySQL InnoDB uses REPEATABLE_READ. Do not assume.

Executor types

TypeBehaviourUse for
SIMPLENew PreparedStatement per callDefault; almost everything
REUSECaches prepared statements by SQL text within the sessionLoops running the same statement repeatedly
BATCHQueues updates, sends them on flushBulk loads
batch with periodic flush
try (SqlSession session = factory.openSession(ExecutorType.BATCH)) {

    UserMapper mapper = session.getMapper(UserMapper.class);

    int count = 0;
    for (User user : hugeList) {
        mapper.insert(user);
        if (++count % 1000 == 0) {
            List<BatchResult> results = session.flushStatements();
            log.debug("flushed {} statements", results.size());
        }
    }
    session.commit();
}
Mixing reads and writes in BATCH mode

A SELECT issued between queued updates forces an implicit flush so the read sees consistent data. Interleaving them defeats the batching entirely — do all the writes first, or use a separate session for the reads.

Under Spring: stop calling commit

mybatis-spring supplies a SqlSessionTemplate that is thread-safe and binds itself to the transaction Spring already started. The rules invert:

StandaloneSpring
Open the sessionYouThe template
CommitYou@Transactional
Rollbackclose() or youOn unchecked exception
Closetry-with-resourcesThe template
IsolationopenSession(level)@Transactional(isolation = …)
OrderService.java — Spring version
@Service
public class OrderService {

    private final OrderMapper orderMapper;
    private final StockMapper stockMapper;

    public OrderService(OrderMapper orderMapper, StockMapper stockMapper) {
        this.orderMapper = orderMapper;
        this.stockMapper = stockMapper;
    }

    @Transactional(isolation = Isolation.READ_COMMITTED, timeout = 10)
    public void placeOrder(Order order, List<OrderLine> lines) {
        orderMapper.insert(order);
        for (OrderLine line : lines) {
            line.setOrderId(order.getId());
            orderMapper.insertLine(line);
            if (stockMapper.decrement(line.getProductId(), line.getQuantity()) == 0) {
                throw new OutOfStockException(line.getProductId());   // triggers rollback
            }
        }
        // no commit() — Spring commits when the method returns
    }
}
Three ways to lose a Spring rollback

Checked exceptions do not roll back by default — add rollbackFor = Exception.class.
Self-invocation: calling this.otherTransactionalMethod() bypasses the proxy entirely.
Swallowed exceptions: a catch block that logs and continues leaves the transaction marked rollback-only, and the commit then fails with UnexpectedRollbackException.

Batch operations inside Spring

The injected mapper uses the default SIMPLE executor. For batch work, declare a second template and use it explicitly.

MyBatisConfig.java
@Configuration
public class MyBatisConfig {

    @Bean
    public SqlSessionTemplate batchSqlSessionTemplate(SqlSessionFactory factory) {
        return new SqlSessionTemplate(factory, ExecutorType.BATCH);
    }
}
BulkImportService.java
@Service
public class BulkImportService {

    private final SqlSessionTemplate batchTemplate;

    public BulkImportService(
            @Qualifier("batchSqlSessionTemplate") SqlSessionTemplate batchTemplate) {
        this.batchTemplate = batchTemplate;
    }

    @Transactional
    public void importUsers(List<User> users) {
        UserMapper mapper = batchTemplate.getMapper(UserMapper.class);
        int i = 0;
        for (User user : users) {
            mapper.insert(user);
            if (++i % 1000 == 0) {
                batchTemplate.flushStatements();
            }
        }
    }
}

Diagnosing connection leaks

  1. SymptomRequests hang, then fail with pool timeouts, usually under moderate load rather than peak.
  2. Enable leak detectionspring.datasource.hikari.leak-detection-threshold=20000 prints the stack trace of the borrower.
  3. Look for the usual suspectsA session opened outside try-with-resources, a Cursor consumed after the session closed, or an async task using a mapper from another thread.
  4. ConfirmWatch hikaricp_connections_active. A metric that only ever climbs is conclusive.

A @Transactional method catches a DataIntegrityViolationException, logs it, and returns normally. What happens at commit?

Once a runtime exception escapes a transactional boundary, the transaction is flagged rollback-only. Catching it further out does not clear the flag, so the eventual commit fails. If a failure is genuinely recoverable, isolate it in its own transaction with REQUIRES_NEW.