Understanding MyBatis First-Level and Second-Level Cache: Principles and Differences
This article explains MyBatis caching mechanisms, detailing the scope, implementation, configuration, and differences between first-level (SqlSession) and second-level (mapper) caches, and how they improve query performance while outlining their default behaviors and usage considerations.
MyBatis provides caching mechanisms to improve query performance by reducing database access.
First‑level cache operates at the SqlSession level; it stores query results within a session and is cleared on commit or when the session ends.
Implementation relies on a local cache inside the Executor, and the cache scope can be configured via the <setting name="localCacheScope" value="STATEMENT"/> element.
Second‑level cache is shared across SqlSessions for the same mapper namespace; it must be explicitly enabled and uses a CachingExecutor to check the global cache before the first‑level cache.
When enabled, the query flow becomes second‑level cache → first‑level cache → database, but it is disabled by default because frequent write operations would invalidate it.
The article also compares the two caches, noting scope, default state, and clearing behavior.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Mike Chen's Internet Architecture
Over ten years of BAT architecture experience, shared generously!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
