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.
The openSession variants
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);
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
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
| Object | Scope | Thread-safe | Rule |
|---|---|---|---|
SqlSessionFactoryBuilder | method | — | Discard after build() |
SqlSessionFactory | application | Yes | Create once, never close |
SqlSession | request / method | No | try-with-resources, never a field |
| Mapper | method | No | Tied to its session; do not cache |
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
// 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
try (SqlSession session = factory.openSession(
TransactionIsolationLevel.REPEATABLE_READ)) {
// ...
}
| Level | Prevents | Still allows |
|---|---|---|
READ_UNCOMMITTED | nothing | dirty reads |
READ_COMMITTED | dirty reads | non-repeatable reads, phantoms |
REPEATABLE_READ | + non-repeatable reads | phantoms (except in InnoDB) |
SERIALIZABLE | everything | — at a real throughput cost |
NONE | uses the driver default | — |
Defaults differ: PostgreSQL and Oracle use READ_COMMITTED, MySQL InnoDB uses
REPEATABLE_READ. Do not assume.
Executor types
| Type | Behaviour | Use for |
|---|---|---|
SIMPLE | New PreparedStatement per call | Default; almost everything |
REUSE | Caches prepared statements by SQL text within the session | Loops running the same statement repeatedly |
BATCH | Queues updates, sends them on flush | Bulk loads |
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();
}
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:
| Standalone | Spring | |
|---|---|---|
| Open the session | You | The template |
| Commit | You | @Transactional |
| Rollback | close() or you | On unchecked exception |
| Close | try-with-resources | The template |
| Isolation | openSession(level) | @Transactional(isolation = …) |
@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
}
}
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.
@Configuration
public class MyBatisConfig {
@Bean
public SqlSessionTemplate batchSqlSessionTemplate(SqlSessionFactory factory) {
return new SqlSessionTemplate(factory, ExecutorType.BATCH);
}
}
@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
- SymptomRequests hang, then fail with pool timeouts, usually under moderate load rather than peak.
- Enable leak detection
spring.datasource.hikari.leak-detection-threshold=20000prints the stack trace of the borrower. - Look for the usual suspectsA session opened outside try-with-resources, a
Cursorconsumed after the session closed, or an async task using a mapper from another thread. - 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.