MyBatis Cache: Purpose & Levels Explained
The purpose of the MyBatis caching mechanism is to improve database query performance by storing query results in memory, which helps avoid redundant database access operations and thereby speeds up data retrieval.
Specifically, the MyBatis cache can be divided into two levels: first-level cache (local cache) and second-level cache (global cache).
- Primary Cache: The primary cache is at the level of the SqlSession, it is enabled by default and is transaction-level cache. Within the same SqlSession, when the same query statement is executed, if the same query result already exists in the cache, the result is directly retrieved from the cache, avoiding unnecessary repeated queries and database accesses.
- Secondary cache: The secondary cache is a cache at the mapper level, which is turned off by default. When the secondary cache is enabled, query results are stored in a shared cache area. This allows different SqlSessions executing the same query statement to retrieve results from the secondary cache, preventing redundant queries and database access operations.
By utilizing caching mechanism, MyBatis can reduce the frequency of database access, improve query performance, especially in the case of multi-table join queries or when dealing with large amounts of data. However, it is important to note that caching can lead to data consistency issues. Therefore, it is necessary to clean the cache promptly after update, insert, delete operations to ensure data accuracy.