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.

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

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.

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.

BackendjavasqlMyBatis
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.