Why MyBatis Runs Extra SQLs and How to Tune Its Cache
This article explains why MyBatis may execute unexpected additional SQL statements, reveals the default caching behavior, shows the required XML configuration and Serializable implementation, and offers practical steps to prevent cache clearing on inserts for more efficient backend data access.
We start by examining a MyBatis example where two SQL statements are issued, leading to the mistaken belief that MyBatis lacks caching.
Reviewing the MyBatis documentation reveals that caching is enabled by default, but additional configuration is required.
The necessary configuration is added to UserMapper.xml, and the domain objects must implement the Serializable interface to avoid a NotSerializableException.
After applying the configuration, an insert operation triggers three SQL statements. This occurs because the insert clears the cache, causing the sequence get(1L) → add() → get(1L) to issue three queries.
Although the insert does not affect the result of subsequent get(1L) calls, clearing the cache is inefficient. To optimize, we can: list queries with low cache‑hit rates are excluded from caching. insert operations no longer clear the cache.
The updated UserMapper.xml reflects these changes, resulting in a more efficient MyBatis caching mechanism.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
