Mybatis's first-level cache and first-level cache

Mybatis's first level cache

The first level cache is the SqlSession level, which is enabled by default and cannot be disabled.

 When operating the database, you need to create a SqlSession object. There is a HashMap in the object to store cached data, and the cached data area between different SqlSessions does not affect each other. Each SqlSession holds an Executor, and each Executor has a LocalCache. When the user initiates a query, MyBatis generates a MappedStatement according to the currently executed statement, and performs the query in the Local Cache. If the cache hits, the result is directly returned to the user. If the cache does not hit, the database is queried, the result is written to the Local Cache, and the result is finally returned. To the user.

In other words, the scope of the first level cache is within the scope of the SqlSession. When the same SQL statement is executed twice in the same SqlSession, the result of the first execution will be stored in the cache, and when the same query is executed the second time, Get it directly from the cache.

If SqlSession performs DML operations (insert, update, delete), the first level cache corresponding to this SqlSession will be invalidated to ensure the validity of the data.

Therefore, there are multiple SqlSessions or in a distributed environment, DML operations will only invalidate the corresponding first-level cache, which may cause the problem of dirty data.

 

Mybatis 's secondary cache

The secondary cache of Mybatis is closed by default.

When using the second-level cache, multiple SqlSessions use the same Mapper SQL statement to operate the database, and the obtained data will be stored in the second-level cache area. The HashMap is also used for data storage. Compared with the first-level cache, the second-level cache has a larger range. Multiple SqlSessions can share the second-level cache. The scope is the same namespace of the Mapper. Different SqlSessions execute the SQL statement under the same namespace twice. If the parameters are equal, the result of the first execution is stored in the second-level cache. , The second execution will directly fetch data from the secondary cache.

Since the secondary cache of Mybatis is based on the namespace, the namespace where the multi-table query statement is located cannot perceive the modification of the tables involved in the multi-table query by other namespaces, which is also prone to dirty data problems.

 

Guess you like

Origin blog.csdn.net/bai_ye_/article/details/107536574