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.
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.
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
}
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:
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,updateordeletein the session — the whole cache, not just the affected statement. session.commit()orsession.rollback().session.clearCache().- A statement declared with
flushCache="true". - Session close.
<settings> <!-- SESSION (default) | STATEMENT --> <setting name="localCacheScope" value="STATEMENT"/> </settings>
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.
<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>
| Attribute | Default | Meaning |
|---|---|---|
eviction | LRU | LRU, FIFO, SOFT, WEAK |
flushInterval | never | Milliseconds before a full flush |
size | 1024 | Maximum number of result objects held |
readOnly | false | true hands out shared instances (fast, unsafe to mutate); false serialises a copy per reader |
blocking | false | true locks the key on a miss so only one thread queries — prevents cache stampedes |
type | PerpetualCache | A custom Cache implementation |
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:
<cache-ref namespace="com.bitsnippets.shop.mapper.OrderMapper"/>
The rules that govern L2
- Global switch
cacheEnabled=falsein settings disables L2 everywhere, regardless of<cache/>. - Per namespaceNo
<cache/>element, no L2 for that mapper. - Per statement
useCache="false"excludes one select;flushCache="true"forces a flush before it runs. - Write-through on commitReads are only visible to other sessions after the writing session commits — uncommitted data never leaks.
- Coarse invalidationAny write in a namespace flushes the entire namespace cache, not just related keys.
When the second level cache is the wrong tool
| Situation | Problem |
|---|---|
| More than one application instance | Each JVM has its own cache; instance B keeps serving data instance A just changed. |
| Another system writes the tables | MyBatis has no idea and never invalidates. |
| Write-heavy tables | Every write flushes everything; the hit ratio approaches zero while you pay the copy cost. |
| Large result sets | size counts objects, not bytes. 1,024 fat graphs can be gigabytes. |
| Per-user or per-tenant filtered data | The 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.
<dependency> <groupId>org.mybatis.caches</groupId> <artifactId>mybatis-redis</artifactId> <version>1.0.0-beta2</version> </dependency>
<cache type="org.mybatis.caches.redis.RedisCache"/>
host=redis.internal port=6379 connectionTimeout=5000 soTimeout=5000 database=0
Writing your own Cache
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
- Start with everything off.
cacheEnabled=false. Measure first. - Find the read-mostly tables. Look for statements with high call counts and near-zero write rates.
- Enable per namespace with a conservative
flushInterval, so staleness is bounded even if invalidation is missed. - Use
cache-refwherever two mappers touch the same table. - Go distributed the moment you run more than one instance.
- Measure the hit ratio. Below roughly 40 %, the cache is costing more than it saves.
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.