Chapter 09

Caching: the two levels

MyBatis has one cache you cannot turn off by accident and one you should not turn on by accident. Knowing the difference prevents both stale data and mysterious test failures.

⏱ 18 min readLevel: intermediate
Two sessions each with their own local cache, both sitting above a shared namespace-level second cache, which sits above the database
L1 is per session and always on. L2 is per mapper namespace, shared, and opt-in.

First level cache (local, per session)

Every SqlSession keeps a PerpetualCache — a plain HashMap. Run the same query with the same parameters twice in one session and the second call never reaches the database.

L1 in action
try (SqlSession session = factory.openSession()) {
    UserMapper mapper = session.getMapper(UserMapper.class);

    User a = mapper.findById(1L);   // SELECT ... (logged)
    User b = mapper.findById(1L);   // cache hit — no SQL

    System.out.println(a == b);     // true: the SAME instance

    b.setEmail("mutated@example.com");
    System.out.println(a.getEmail()); // "mutated@example.com" — a and b are one object
}
L1 returns the same instance, not a copy

Mutating a cached object changes what every other reader in that session sees. If your service layer modifies returned entities in place, either copy them, or set localCacheScope=STATEMENT.

What makes up the cache key

Five components. Any difference means a miss:

CacheKey composition
1. MappedStatement id      com.bitsnippets.shop.mapper.UserMapper.findById
2. RowBounds offset/limit  0 / 2147483647
3. The final SQL text      SELECT ... WHERE id = ?
4. All parameter values    1(Long)
5. The environment id      development

This is why two dynamic-SQL calls with different active branches never collide: the SQL text itself is part of the key.

When L1 is cleared

  • Any insert, update or delete in the session — the whole cache, not just the affected statement.
  • session.commit() or session.rollback().
  • session.clearCache().
  • A statement declared with flushCache="true".
  • Session close.
turning L1 off per session
<settings>
  <!-- SESSION (default) | STATEMENT -->
  <setting name="localCacheScope" value="STATEMENT"/>
</settings>
Where L1 surprises people

In Spring, a session usually spans one @Transactional method. A long transaction that reads a row, waits, and reads it again will get the first snapshot even if another transaction committed a change in between. When you genuinely need a fresh read, mark the statement flushCache="true".

Second level cache (namespace)

Shared by all sessions, scoped to a mapper namespace, and — critically — populated only when the writing session commits. That transactional behaviour is what makes it safe within one JVM and dangerous across many.

ProductMapper.xml
<mapper namespace="com.bitsnippets.shop.mapper.ProductMapper">

  <cache eviction="LRU"
         flushInterval="600000"
         size="1024"
         readOnly="false"
         blocking="false"/>

  <select id="findById" resultType="Product" useCache="true">
    SELECT id, sku, name, price FROM product WHERE id = #{id}
  </select>

  <!-- writes flush the whole namespace cache -->
  <update id="updatePrice" flushCache="true">
    UPDATE product SET price = #{price} WHERE id = #{id}
  </update>

</mapper>
AttributeDefaultMeaning
evictionLRULRU, FIFO, SOFT, WEAK
flushIntervalneverMilliseconds before a full flush
size1024Maximum number of result objects held
readOnlyfalsetrue hands out shared instances (fast, unsafe to mutate); false serialises a copy per reader
blockingfalsetrue locks the key on a miss so only one thread queries — prevents cache stampedes
typePerpetualCacheA custom Cache implementation
readOnly="false" requires Serializable

The default deep-copies cached values by serialisation, so every mapped class — and every nested class inside it — must implement java.io.Serializable. Miss one and you get a NotSerializableException the first time the cache is read, typically in production rather than in tests.

cache-ref: sharing across namespaces

UserMapper and OrderMapper both touch customer_order. If only one declares a cache, the other's writes will not flush it and you serve stale data. Point them at the same cache instead:

UserMapper.xml
<cache-ref namespace="com.bitsnippets.shop.mapper.OrderMapper"/>

The rules that govern L2

  1. Global switchcacheEnabled=false in settings disables L2 everywhere, regardless of <cache/>.
  2. Per namespaceNo <cache/> element, no L2 for that mapper.
  3. Per statementuseCache="false" excludes one select; flushCache="true" forces a flush before it runs.
  4. Write-through on commitReads are only visible to other sessions after the writing session commits — uncommitted data never leaks.
  5. Coarse invalidationAny write in a namespace flushes the entire namespace cache, not just related keys.

When the second level cache is the wrong tool

SituationProblem
More than one application instanceEach JVM has its own cache; instance B keeps serving data instance A just changed.
Another system writes the tablesMyBatis has no idea and never invalidates.
Write-heavy tablesEvery write flushes everything; the hit ratio approaches zero while you pay the copy cost.
Large result setssize counts objects, not bytes. 1,024 fat graphs can be gigabytes.
Per-user or per-tenant filtered dataThe key includes parameters, so the cache fragments into thousands of one-hit entries.

Good candidates are small, read-mostly reference tables: currencies, countries, product categories, feature flags, tax rates.

Distributed caching with Redis

The mybatis-redis adapter replaces the in-JVM map with a shared store, which fixes the multi-instance problem.

pom.xml
<dependency>
  <groupId>org.mybatis.caches</groupId>
  <artifactId>mybatis-redis</artifactId>
  <version>1.0.0-beta2</version>
</dependency>
ProductMapper.xml
<cache type="org.mybatis.caches.redis.RedisCache"/>
redis.properties
host=redis.internal
port=6379
connectionTimeout=5000
soTimeout=5000
database=0

Writing your own Cache

MetricsCache.java
package com.bitsnippets.shop.cache;

import org.apache.ibatis.cache.Cache;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;

/** A minimal cache that also reports hit and miss counts. */
public class MetricsCache implements Cache {

    private final String id;
    private final ConcurrentHashMap<Object, Object> store = new ConcurrentHashMap<>();
    private final LongAdder hits   = new LongAdder();
    private final LongAdder misses = new LongAdder();

    // MyBatis requires this exact constructor signature
    public MetricsCache(String id) {
        this.id = id;
    }

    @Override public String getId() { return id; }

    @Override public void putObject(Object key, Object value) { store.put(key, value); }

    @Override public Object getObject(Object key) {
        Object value = store.get(key);
        if (value == null) { misses.increment(); } else { hits.increment(); }
        return value;
    }

    @Override public Object removeObject(Object key) { return store.remove(key); }

    @Override public void clear() { store.clear(); }

    @Override public int getSize() { return store.size(); }

    public double hitRatio() {
        long h = hits.sum(), m = misses.sum();
        return (h + m) == 0 ? 0 : (double) h / (h + m);
    }
}

Register it with <cache type="com.bitsnippets.shop.cache.MetricsCache"/>. MyBatis wraps whatever you supply in its own decorator chain — logging, synchronisation, transactional buffering — so your implementation does not need to be thread-safe for correctness, only for performance.

A caching strategy that survives contact with production

  1. Start with everything off.cacheEnabled=false. Measure first.
  2. Find the read-mostly tables. Look for statements with high call counts and near-zero write rates.
  3. Enable per namespace with a conservative flushInterval, so staleness is bounded even if invalidation is missed.
  4. Use cache-ref wherever two mappers touch the same table.
  5. Go distributed the moment you run more than one instance.
  6. Measure the hit ratio. Below roughly 40 %, the cache is costing more than it saves.
Consider caching one layer up instead

Spring's @Cacheable on a service method caches the finished DTO, keyed by business identity rather than SQL text. It is easier to reason about, easier to invalidate precisely, and does not interact with transactions in surprising ways. MyBatis L2 is the right answer less often than you would think.

Session A caches a product. Session B updates that product and commits. What does session A see on its next read?

Within one JVM, any committed write in a namespace flushes that namespace's entire L2 cache, so the next read goes to the database. The stale-data risk appears when the writer is a different JVM or an external system — which is exactly why you need a distributed provider once you scale out.