MyBatis study notes (9) cache

 

In high-concurrency applications, in order to improve the access speed and reduce the access to the database , the cache mechanism can be used.

MyBatis cache is divided into first-level cache and second-level cache

 

The scope of the Mybatis 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 data obtained from the cache will not be queried from the database for the second time, thus improving the 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 .

Mybatis secondary cache is shared by multiple SqlSessions , and its scope is the same as that of mappernamespace , different sqlSession executes the sql statement under the same namespace twice and passes the same parameters to 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) . The data obtained from the cache for the second time will no longer be queried from the database, thereby improving the query efficiency. Mybatis does not enable the second-level cache by default. You need to configure the second-level cache in the setting global parameter.

L1 cache

The first- level cache area is divided according to the SqlSession unit .

Each query will first find it from the cache area. If the query from the database cannot be found, the query will write the data to the cache.

Mybatis internal storage cache uses a HashMap , the key is hashCode+sqlId+Sql statement. value is the java object generated from the query out of the map .

After sqlSession executes operations such as insert , update , delete and commit , the cache area will be cleared.

test

 

//get session
SqlSession session = sqlSessionFactory.openSession();
//Restricted mapper interface instance
UserDao dao = session.getMapper(UserDao.class);
// first query
User user1 = dao.findUserById(1);
System.out.println(user1);
//The second query, because it is the same session, it will no longer issue a statement to the data and retrieve it directly from the cache
User user2 = dao.findUserById(1);
System.out.println(user2);
//Close the session
session.close();

 As can be seen from the SQL information on the console, the SQL statement is only sent once.

 

 

 

//get session
SqlSession session = sqlSessionFactory.openSession();
//Restricted mapper interface instance
UserDao dao = session.getMapper(UserDao.class);
// first query
User user1 = dao.findUserById(1);
System.out.println(user1);
// perform the update in the same session
User user_update = new User();
user_update.setId(1);
user_update.setUsername("李奎");
dao.updateUser(user_update);
session.commit();
//The second query, although it is the same session, but the cache of the session is emptied due to the update operation, and the sql operation is reissued here
User user2 = dao.findUserById(1);
System.out.println(user2);

 As can be seen from the SQL information on the console, the SQL statement for 2 queries was sent.

 

L2 cache

The second- level cache area is divided according to the mapper 's namespace . The mapper query data of the same namespace are placed in the same area. If the mapper proxy method is used, the namespace of each mapper is different. At this time, it can be understood that the second-level cache area is divided according to the mapper . .

Each query will first find it from the cache area. If the query from the database cannot be found, the query will write the data to the cache.

Mybatis internal storage cache uses a HashMap , the key is hashCode+sqlId+Sql statement. value is the java object generated from the query map

After sqlSession executes operations such as insert , update , delete and commit , the cache area will be cleared.

 

Enable L2 cache

Add to the core configuration file mybatis-config.xml :

<setting name="cacheEnabled" value="true"/>

 

describe

allowance

Defaults

cacheEnabled

Global on / off settings for all caches under this configuration file .

true false

true

 

To add a line to your Mapper mapping file:   <cache />  , indicating that this mapper enables L2 cache.

 

implement serialization

The second-level cache requires the POJO object mapped by the query result to implement the java.io.Serializable interface to implement serialization and deserialization operations. Note that if there is a parent class and member pojo , the serialization interface needs to be implemented.

      public class Orders implements Serializable

               public class User implements Serializable

 

test

//Get session1
SqlSession session1 = sqlSessionFactory.openSession();
UserMapper userMapper = session1.getMapper(UserMapper.class);
//Use session1 to execute the first query
User user1 = userMapper.findUserById(1);
System.out.println(user1);
//Close session1
session1.close();
//Get session2
SqlSession session2 = sqlSessionFactory.openSession();
UserMapper userMapper2 = session2.getMapper(UserMapper.class);
//Use session2 to execute the second query. Since the second-level cache is turned on, the data obtained from the cache is no longer issued to the database.
User user2 = userMapper2.findUserById(1);
System.out.println(user2);
//Close session2
session2.close();

 

live

Disable L2 cache

existSetting useCache=false in the statement can disable the secondary cache of the current select statement, that is, every query will send sql to query, the default is true , that is, the sql uses the secondary cache.

<select id="findOrderListResultMap" resultMap="ordersUserMap" useCache="false">

flush cache

In the same namespace of mapper , if there are other insert , update , delete operation data, the cache needs to be refreshed . If the cache refresh is not performed , dirty reads will occur .

Set the flushCache="true"  property in the statement configuration. By default, it is true to refresh the cache. If it is changed to false , it will not be refreshed. Dirty reads will occur if the query data in the database table is manually modified when using the cache .

as follows:

<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User" flushCache="true">

 Mybatis Cache parameters

flushInterval can be set to any positive integer, and they represent a reasonable time period in milliseconds . The default is not set, that is, there is no refresh interval, the cache is only refreshed when the statement is called.

size (number of references) can be set to any positive integer, keeping in mind the number of objects you cache and the number of available memory resources in your runtime environment. The default value is 1024 .

The readOnly (read-only) property can be set to true or false . A read-only cache will return the same instance of the cache object to all callers. Therefore these objects cannot be modified. This provides a significant performance advantage. A read-write cache returns a copy of the cached object (via serialization). This will be slower , but safe , so the default is false .

 

The following example:

<cache  eviction="FIFO"  flushInterval="60000"  size="512"  readOnly="true"/>

This more advanced configuration creates a  FIFO  buffer that is flushed every  60  seconds , holding  512  references to the result object or list , and the returned object is considered read-only , so between callers in different threads Modifying them will cause conflicts. The available eviction strategies are , the default is  LRU : 

<!--[if !supportLists]--> 1.          <!--[endif]--> LRU  Least Recently Used : Remove objects that have not been used for the longest time. 

<!--[if !supportLists]--> 2.          <!--[endif]--> FIFO  - FIFO : Remove objects in the order they entered the cache. 

<!--[if !supportLists]--> 3.          <!--[endif]--> SOFT  Soft Reference : Remove objects based on garbage collector state and soft reference rules. 

<!--[if !supportLists]--> 4.          <!--[endif]--> WEAK  Weak References : More aggressively remove objects based on garbage collector state and weak reference rules. 

 

 

Guess you like

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