This is the 23rd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Mybatis secondary Cache source code Cache tag parsing

Mybatis cache structure diagram

As can be seen from the above figure, level-2 cache is built on level-1 cache. When receiving a query request, MyBatis will first query level-2 cache. If level-2 cache fails to hit, MyBatis will query level-2 cache. The order is level 2 cache — level 1 cache — database

Unlike level-1 caches, level-2 caches are bound to a specific namespace. A Mapper has a Cache and the MappedStatement in the same Mapper shares the same Cache. Level-1 caches are bound to SqlSession. A Mapper may have multiple SQLSessions, but only one Cache.

How do I enable level 2 caching

  • Enable the global level-2 cache configuration
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
Copy the code
  • Configure labels in Mapper profiles that need to use level 2 caching
<cache></cache>
Copy the code
  • Set useCache=true on specific CURD tags
<select id="findById" resultType="com.test.pojo.User" useCache="true">
select * from user where id = #{id}
</select>
Copy the code

Tag < cache /> source parsing

How to parse cache label attributes

According to the first two Mybatis source code analysis, we can know that XML parsing is mainly handed to the xmlConfigBuilder.parse () method to achieve.

Because the tag Chache is configured in mapper’s mapping configuration file, we’ll look directly at the parsing of the Mappers tag

The XMLMapperBuilder configuration file is used to parse the mapping configuration file by executing the mapperParser.parse() method

The cache tag is parsed through the configurationElement method.

There are two cache-related methods: the cacheRefElement method, which resolves the cache-ref tag and introduces other caches into the current mapper, and the cacheRefElement method, which resolves the cache tag

The cacheRefElement method parses all of the attributes in the cache tag and constructs a cache object from those attributes using the useNewCache method. The cache tag parsing is complete

How to build a Cache object

We see a Mapper. Parses XML will only a label, is to create a Cache object, only into the configuration, and give MapperBuilderAssistant Cache assignment. CurrentCache

We see that the Cache object created in the Mapper is added to each MappedStatement object, that is, all the Cache objects in the same Mapper.

At this point, Cache tag source parsing has been completed, will be further analyzed tomorrow