What are the functions of MyBatis first-level cache and second-level cache?
The functions of MyBatis first-level cache and second-level cache are as follows:
- Level one cache: The level one cache is enabled by default in MyBatis. It is a cache at the SqlSession level, also known as local cache. When the same query statement is executed within the same SqlSession, if there are no insert, update, or delete operations performed, MyBatis will directly retrieve the result from the cache without needing to send another query request to the database, thus improving performance. The scope of the level one cache is very limited, only within the same SqlSession.
- Second-level cache: The second-level cache is a cache at the SqlSessionFactory level, also known as a global cache. When multiple SqlSessions share the same SqlSessionFactory, they can share the same second-level cache. The second-level cache can span multiple SqlSessions, providing a higher cache efficiency. When executing a query statement, MyBatis first looks for data in the second-level cache. If it is found, it is returned directly; if not found, a database query is executed and the query result is stored in the second-level cache. The scope of the second-level cache is broader and can span multiple SqlSessions.
In conclusion, both first-level cache and second-level cache can improve query performance and reduce database access times. However, the first-level cache has a smaller scope, limited to the same SqlSession, while the second-level cache has a wider scope, spanning multiple SqlSessions.