Caching

Harry · 11 Sep 2026 · 10 views

Two Levels of Cache

MyBatis ships with two in-memory caches to avoid re-running the same SQL.

First-Level Cache (Session)

Enabled by default, it caches query results inside a single SqlSession. The same query repeated in one session hits the cache. The cache is cleared on any update within the session.

Second-Level Cache (Global, Per-Mapper)

Opt-in via the mapper's <cache/> tag. Results are shared across sessions for that mapper.

<mapper namespace="com.example.app.mapper.CustomerMapper">
  <cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>
  ...
</mapper>
  • eviction: LRU, FIFO, SOFT or WEAK strategy.
  • flushInterval: milliseconds until the cache refreshes.
  • size: maximum number of cached objects.
  • readOnly: true shares immutable objects, fastest.

Cache Helpers and Caveats

  • Statements can opt out with useCache="false" or flush with flushCache="true".
  • Do not enable the second-level cache for mutable shared data without serious thought.
  • <cache-ref namespace="..."> shares one cache across mappers.

Key Points

  • Level 1 caches within a session automatically.
  • Level 2 caches across sessions per mapper, opt-in.
  • Configure eviction, TTL, size and read-only behaviour.
  • Consider caching only for stable, frequently-read data.
Share this post:

Comments (0)

Please login or register to comment.