MyBatis first-level cache and second-level cache (transfer)

Author: little fly Source: http://www.cnblogs.com/little-fly/ Welcome to reprint

 

 

L1 cache

  MyBatis will establish a simple cache in the SqlSession object representing the session, and cache the results of each query. When the next query is made, if it is judged that there is an exact same query before, it will directly store the results from the cache. Take it out and return it to the user, no need to query the database again.

 

  MyBatis will create a local cache (local cache) in the representation of a session - a SqlSession object. For each query, it will try to find whether it is in the cache in the local cache according to the query conditions. If it is in the cache, directly Take it out of the cache and return it to the user; otherwise, read the data from the database, store the query result in the cache and return it to the user.

 

  The first level cache is the SqlSession level cache. When operating the database, the sqlSession object needs to be constructed, and there is a (memory area) data structure (HashMap) in the object for storing cached data. The cached data areas (HashMap) between different sqlSessions do not affect each other.

 

  The scope of the first-level cache is the same SqlSession, and the same sql statement is executed twice in the same sqlSession. After the first execution, the data queried in the database will be written to the cache (memory), and the second time will get the data from the cache. Will no longer query from the database, thus improving query efficiency. When a sqlSession ends, the first-level cache in the sqlSession does not exist. MyBatis turns on the first level cache by default.

 

L2 cache

  The second-level cache is a mapper-level cache . Multiple SqlSessions operate the sql statement of the same Mapper, and multiple SqlSessions operate the database to obtain data. There will be a second-level cache area. Multiple SqlSessions can share the second-level cache. SqlSession.

 

  The second-level cache is shared by multiple SqlSessions, and its scope is the same namespace of mapper. Different sqlSessions execute the sql statement under the same namespace twice and pass the same parameters to the sql, that is, the same sql statement is finally executed. After the first execution, the data queried in the database will be written to the cache (memory), and the data will be obtained from the cache for the second time, and will no longer be queried from the database, thereby improving query efficiency. MyBatis does not open the second-level cache by default. You need to configure the second-level cache in the setting global parameter.


 

If there is data in the cache, it does not need to be obtained from the database, which greatly improves the system performance.

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326895134&siteId=291194637