Understanding MyBatis First-Level and Second-Level Caches with Code Examples

This article explains the concepts of MyBatis first-level and second-level caches, demonstrates how they work with practical Java code, shows configuration methods, and highlights important considerations such as cache invalidation and eviction policies.

Top Architect
Top Architect
Top Architect
Understanding MyBatis First-Level and Second-Level Caches with Code Examples

Cache is temporary data stored in memory; only key data is cached to reduce database load and improve response speed.

In BS architecture, most operations are CRUD; queries are frequent, so caching stores query results in memory after the first DB access.

Typical data cached includes dictionaries, system parameters, status codes, and user login info for fast response.

MyBatis First-Level Cache

MyBatis provides two types of cache: first-level (session) and second-level (global). First-level cache is enabled by default and lives within a SqlSession; any insert/update/delete clears it.

Reader reader = Resources.getResourceAsReader("config/configuration.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// ... operations ...
sqlSession.clearCache();
sqlSession.close();

Testing shows that two identical queries within the same session result in only one database hit, confirming first-level cache effectiveness.

When a query is followed by an update and then another query, the cache is invalidated, leading to three SQL statements.

MyBatis Second-Level Cache

Second-level cache is global, shared across sessions, and must be explicitly enabled either per mapper or for all mappers.

Configuration per mapper:

<!-- Enable second-level cache for a mapper -->
<cache />

Configuration for all mappers (in mybatis.xml):

<settings>
    <!-- <setting name="cacheEnabled" value="true"/> -->
</settings>

Example code demonstrates opening two sessions, performing queries, and observing that the second query retrieves data from the second-level cache without hitting the database.

Important Notes

All select statements' results are cached.

Insert, update, delete statements flush the cache.

Cache eviction uses LRU algorithm.

Cache does not refresh on a timer.

Cache stores up to 1024 object references.

Cache is read/write; retrieved objects can be safely modified.

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.

JavacacheBackend DevelopmentMyBatisFirst-Level CacheSecond-Level Cache
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

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.