MyBatis Cache Guide
There are several main types of caching mechanisms in MyBatis.
- First-level cache: also known as local cache, is the caching mechanism that MyBatis opens by default, and operates at the session level. When performing a query operation, the result will be cached in the internal data structure of the current session. When the same query operation is executed again, the result will be retrieved from the cache, avoiding another database access and improving query performance. The lifespan of the first-level cache is bound to the session, meaning the cache will become invalid once the session is closed.
- Secondary Cache, also known as global cache, is a cache mechanism shared among multiple sessions. When the secondary cache is enabled, different sessions can share the same cache, reducing the number of database accesses and improving system performance. The lifecycle of the secondary cache is the same as the entire lifecycle of the application. The cache is created and destroyed when the application starts and shuts down.
- Custom cache: MyBatis offers an extension interface for custom caching, allowing users to implement their own caching mechanisms based on their needs. You can define your own cache mechanism by implementing the Cache interface and configuring the use of your custom cache implementation in MyBatis configuration file.
It is important to note that caching is not suitable for all query scenarios. In some cases, using cache may result in data inconsistency issues, so it is necessary to configure and use caching based on specific business scenarios.