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.

Programmer DD
Programmer DD
Programmer DD
Why MyBatis Runs Extra SQLs and How to Tune Its Cache

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.

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.

JavaCacheSQLMyBatisORM
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

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.