[mybatis] mybatis cache

Time:2020-12-5

Mybatis cache

  1. The first level cache of mybatis refers to sqlsession. The storage scope is session, and the same SQL statement will be cached by session to improve the execution efficiency. The scope of level 1 cache is a sqlsession. Mybatis turns on the first level cache by default. In the same sqlsession, execute the same query SQL, query the database for the first time and write it to the cache; for the second time, it will be fetched directly from the cache. When SQL is executed, the cache of sqlsession will be emptied if the operations of adding, deleting and modifying occur between the two queries.
  2. Mybatis’s secondary cache refers to the mapper mapping file. The scope of level 2 cache is the content of mapper mapping file in the same namespace, and shared by multiple sqlsessions. Mybatis needs to manually set up the startup L2 cache. In the mapper file under the same namespace, execute the same query SQL, query the database for the first time and write it to the cache; for the second time, retrieve it directly from the cache. When SQL is executed, the second level cache will be emptied if the operations of adding, deleting and modifying occur between the two queries.
  3. The first level cache area is divided by sqlsession. Each query will first go to the cache to find, if not found, then go to the database query, and then write the results to the cache. The internal cache of mybatis uses a HashMap, and the key is hashcode + statementid + SQL statement. Value is the Java object mapped to the query result set. Sqlsession will clear the sqlsession cache after it executes operations such as insert, update and delete.
  4. The L2 cache is mapper level. Mybatis does not have L2 cache enabled by default.

It is the first time to call SQL under mapper to query user information. The query information will be stored in the secondary cache area corresponding to the mapper.

The second time, the same SQL in the mapper mapping file under the same namespace is called to query the user information. The corresponding L2 cache will be fetched.

If you call add, delete and modify SQL in the mapper mapping file under the same namespace, and execute the commit operation. The secondary cache under the namespace is cleared.