Understanding MyBatis First-Level and Second-Level Caches: Principles, Implementation, and Differences

This article explains the principles, implementation steps, and configuration of MyBatis first‑level (SqlSession) and second‑level (mapper) caches, compares their scopes and behaviors, and provides practical guidance on when and how to enable each cache to improve database query performance.

Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Mike Chen's Internet Architecture
Understanding MyBatis First-Level and Second-Level Caches: Principles, Implementation, and Differences

MyBatis Cache

Cache refers to data stored in memory, often the result of database queries, used to avoid frequent database access and improve response speed.

MyBatis provides caching support, divided into first-level (SqlSession) and second-level (mapper) caches.

MyBatis First-Level Cache

1. Why a First-Level Cache Is Needed

When using MyBatis, a SqlSession is created for each database session. If the same SQL statement is executed multiple times, repeatedly querying the database wastes resources.

The first-level cache stores query results within the same SqlSession, so identical SQL statements can be served from memory.

2. Implementation of the First-Level Cache

MyBatis executes statements through an Executor whose lifecycle matches the SqlSession. Inside the Executor, a local cache (first-level cache) is created.

The typical workflow is:

First query: check the cache; if missing, query the database, then store the result in the first-level cache.

If a commit operation (insert, update, delete) occurs, the first-level cache is cleared to prevent dirty reads.

Second query: if the result is already in the cache, it is returned directly.

Note that both queries must occur within the same SqlSession; otherwise the first-level cache is not used.

3. Configuration of the First-Level Cache

The cache scope can be SESSION (default) or STATEMENT. Setting it to STATEMENT clears the cache after each statement execution.

You can change the scope in the MyBatis configuration file using the localCacheScope setting, for example:

<setting name="localCacheScope" value="STATEMENT"/>

MyBatis Second-Level Cache

1. Why a Second-Level Cache Is Needed

The first-level cache is limited to a single SqlSession. To share cached data across multiple SqlSessions, the second-level cache must be enabled.

2. Implementation of the Second-Level Cache

When enabled, MyBatis decorates the Executor with a CachingExecutor. Before the first-level cache is consulted, the second-level cache is checked.

All statements under the same namespace share a single cache instance, making it a global cache for that mapper.

The query flow becomes: second-level cache → first-level cache → database.

MyBatis disables the second-level cache by default because frequent write operations would constantly invalidate it.

Differences Between First-Level and Second-Level Caches

First-Level Cache : Scoped to a SqlSession, enabled by default. It stores query results in a HashMap keyed by statement ID and parameters. The cache is cleared when a commit occurs or when the scope is set to STATEMENT.

Second-Level Cache : Scoped to a mapper (namespace) and shared across SqlSessions. It must be manually enabled in the mapper XML. It provides a broader cache that can be reused by different sessions but is turned off by default.

Both caches aim to reduce database load, but they operate at different levels and have distinct configuration requirements.

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.

BackendJavacacheMyBatisFirst-Level CacheSecond-Level Cache
Mike Chen's Internet Architecture
Written by

Mike Chen's Internet Architecture

Over ten years of BAT architecture experience, shared generously!

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.