Understanding MyBatis Caching: First‑Level, Second‑Level, and Custom Cache Implementations

This article explains the core concepts of MyBatis caching, details how first‑level and second‑level caches work, shows configuration options, illustrates cache invalidation scenarios, and demonstrates custom cache integration with EHCache through practical code examples and test questions.

Wukong Talks Architecture
Wukong Talks Architecture
Wukong Talks Architecture
Understanding MyBatis Caching: First‑Level, Second‑Level, and Custom Cache Implementations

This article introduces the essential concepts of MyBatis caching, including the purpose of the cache, the role of SqlSession, MappedStatement, Executor, and the namespace used for mapper‑level cache sharing.

1. First‑Level Cache

The first‑level cache lives inside a single SqlSession. When the same query is executed repeatedly within the same session without any intervening insert, update, or delete, the result is retrieved from a LocalCache (a simple HashMap) instead of hitting the database.

Key generation example:

private Map<Object, Object> cache = new HashMap<>();

Cache key format: StatementId + Offset + Limit + Sql + Params Configuration in mybatis-config.xml:

<configuration>
    <settings>
        <setting name="localCacheScope" value="SESSION"/>
    </settings>
</configuration>
SESSION

enables first‑level caching for the whole session, while STATEMENT disables it for individual statements.

Typical invalidation scenarios:

Different SqlSession instances (each has its own cache).

Different query conditions within the same session.

Any insert, update, or delete operation between two queries.

Manual cache clearing.

Test questions illustrate these rules, e.g., three identical queries in one session hit the cache, but a modification between queries forces a database hit.

2. Second‑Level Cache

The second‑level cache is shared across multiple SqlSession instances at the namespace level. It is implemented by decorating the Executor with a CachingExecutor, which checks the second‑level cache before the first‑level cache.

Cache lookup order:

Check second‑level cache.

If miss, check first‑level cache.

If still miss, query the database.

When the session closes, data from the first‑level cache is written to the second‑level cache.

Enable it in mybatis-config.xml:

<setting name="cacheEnabled" value="true"/>

Declare a cache in a mapper XML file:

<cache type="org.apache.ibatis.caches.ehcache.EhcacheCache"/>

Because the second‑level cache is namespace‑scoped, it is unsuitable for multi‑table queries that may cause dirty data in distributed environments.

3. Custom Cache and EHCache Integration

When the built‑in second‑level cache does not meet requirements, developers can implement the org.apache.ibatis.cache.Cache interface (seven methods) to provide a custom caching strategy.

EHCache integration example:

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>

Sample ehcache.xml configuration (disk store, memory limits, TTL, etc.) is shown in the source.

After adding the dependency and configuration, the mapper XML can reference the EHCache implementation with the <cache> tag shown above.

4. Summary

The article covered MyBatis first‑level and second‑level cache mechanisms, configuration options, cache invalidation cases, and how to create a custom cache using EHCache. Four practice questions were provided to reinforce understanding, though the source code of MyBatis cache itself was not examined.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaCacheMyBatis
Wukong Talks Architecture
Written by

Wukong Talks Architecture

Explaining distributed systems and architecture through stories. Author of the "JVM Performance Tuning in Practice" column, open-source author of "Spring Cloud in Practice PassJava", and independently developed a PMP practice quiz mini-program.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.