MyBatis Cache Explained
The purpose of MyBatis caching is to improve system performance by reducing the number of database interactions and easing the burden on the database. By caching query results in memory, it can prevent repeated querying of the database, thus enhancing system response speed.
The caching mechanism of MyBatis involves controlling cache at both the SqlSession layer and the second-level cache layer. At the SqlSession layer, MyBatis utilizes PerpetualCache to implement a HashMap-based caching model, storing query results in memory. At the second-level cache layer, MyBatis supports storing cache in external cache systems like Redis or Ehcache.
The caching mechanism of MyBatis is based on the following principles:
- By default, MyBatis will create a cache for each query of each mapper, and the cache’s lifecycle is the same as the SqlSession’s lifecycle.
- In the same SqlSession, if the input parameters and SQL statements of two queries are exactly the same, the second query will directly retrieve the results from the cache without executing a database query again.
- Any modifications (such as insertions, updates, deletions) between two queries in the same SqlSession will result in clearing the mapper’s cache.
It’s important to note that MyBatis’ cache mechanism is based on object references, meaning it caches references to the queried result objects rather than copies of them. Therefore, when using MyBatis cache, it’s important to consider the mutability of the returned result objects to avoid external modifications to cached objects affecting other query results.