Mybatis basics (eight) query cache

Mybatis basics (eight)

Query cache

Level 1 cache (included with Mybatis)

The first level cache puts the query information in the SqlSession object, and the SqlSession object in the memory.
Insert picture description here

Level 1 cache cleaning

whenUse the commit method of the SqlSession object, The data in the SqlSession object is cleared.

Level 2 cache (need to be opened manually)

The source of the secondary cache:

  • Mybatis's own secondary cache
  • Third-party secondary cache

Mybatis's own secondary cache

The mapper objects generated by the same namespace (attributes of the mapper tag) share the cache.

StudentMapper studentMapper = session.getMapper(StudentMapper.class);
StudentMapper studentMapper2 = session.getMapper(StudentMapper.class);

studentMapper and studentMapper2 share the same buffer area. Because Mapper is determined by the mapper class name and registration (that is, namespace).

note! The second-level cache is different from the first-level cache in that the data in the second-level cache is stored in the hard disk. So the serialization class will be called.

After the query, the query result will be serialized to the hard disk (second-level cache), so the query result class should be serialized.
Insert picture description here

Turn on secondary cache

  1. Configure the conf.xml file
<settings>
	<setting name="cacheEnabled" value="true"/>
</settings>
  1. Declare to be turned on in the specific mapper.xml
<!-- 该mapper操作Student -->
<mapper namespace="pers.qiu.StudentMapper">
	<cache/>
</mapper>
  1. Implement serialization interface
class Student implements Serializable{
    
    
    
}

// 如果Student类中有其他类作为属性,则应该级联进行序列化。例如Student中有StudentCard对象作为属性:
class StudentCard implements Serializable{
    
    
    
}

Cache timing

The time for Mybatis to cache is when the session object is closed, that is, when session.close().(Unlike the first level cache, the first level cache is automatically stored in the cache)

Disable the second level cache

Using the cache tag in the mapper file is to enable the second-level cache for all methods in the entire mapper, but sometimes we need to disable the second-level cache for some methods.

<mapper namespace="">
	<cache/>
    <select id="xxx1" xxx>
    	xxx
    </select>
    
    <select id="xxx2" xxx useCache="false">
    	xxx
    </select>
</mapper>

Through the above methods, the xxx2 method turns off the second-level cache. And xxx1 and other unclosed methods both open the second-level cache.

Clean up the secondary cache

Same as the first level cache, use the commit method to clean up the cache.

Guess you like

Origin blog.csdn.net/qq_43477218/article/details/113097183