What do the MyBatis first-level cache and second-level cache refer to?

The MyBatis first level cache and second level cache are two caching mechanisms designed to enhance the query performance of MyBatis.

The first-level cache is the caching mechanism that MyBatis enables by default. It operates at the SqlSession level, meaning that queries performed within the same SqlSession object will be cached. This cache is based on object references, so if the parameters of two queries are the same within the same SqlSession, the second query will directly retrieve the result from the first-level cache without needing to send the SQL statement to the database again. The lifecycle of the first-level cache is the same as that of the SqlSession, and it will be cleared when the SqlSession is closed.

The second-level cache is a cache at the SqlSessionFactory level, which means that different SqlSessions can share the same second-level cache. The second-level cache is implemented based on object serialization, when a query result is put into the second-level cache, it will be serialized into a byte stream and saved in memory. When other SqlSessions perform the same query, they will try to retrieve the result from the second-level cache. If the cache exists, the result will be returned directly, otherwise a SQL statement will be sent to the database. The lifecycle of the second-level cache is the same as the SqlSessionFactory, and it will be cleared when the application closes.

It is important to note that enabling the second-level cache by default requires manual configuration. Additionally, in certain special cases, the second-level cache may not be utilized, such as with queries that involve dynamic SQL statements or utilize unique querying methods.

bannerAds