Understanding MyBatis First‑Level and Second‑Level Caches and Their Integration with Spring Boot
This article explains MyBatis's two‑level caching mechanism, detailing how first‑level session cache works, why it often fails in Spring Boot without transactions, how to enable and configure second‑level cache, and the potential pitfalls of cache inconsistency across mapper namespaces.
MyBatis provides a two‑level caching mechanism—first‑level (session) cache and second‑level (mapper) cache—to improve query performance.
First‑level cache works only within the same SqlSession ; it is enabled by default but requires identical SQL, parameters, mapper namespace, and no intervening insert / update / delete or cache‑clearing calls such as session.clearCache() .
When MyBatis is used with Spring Boot, each query often creates a new SqlSession , so the first‑level cache does not take effect unless a transaction (e.g., @Transactional ) keeps the same session.
Second‑level cache is disabled by default and must be enabled in the configuration (e.g., mybatis-plus: configuration: cache-enabled: true ) and on the mapper with @CacheNamespace ; cached objects must implement Serializable .
Second‑level cache is populated after the SqlSession commits or closes and is shared across sessions but scoped by mapper namespace, which can cause stale data when different mappers modify related tables.
Examples illustrate how to configure the caches, use code snippets such as member_id queries, and demonstrate pitfalls like cache inconsistency after updates across namespaces, ultimately recommending caution when using second‑level cache.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.