MyBatis: Cache for MyBatis

1. MyBatis first level cache

  • The first-level cache is at the SqlSession level. The data queried through the same SqlSession will be cached. The next time the same data is queried, it will be obtained directly from the cache and will not be re-accessed from the database.
  • Four situations that invalidate the L1 cache:
    1. Different SqlSession s correspond to different first-level caches
    2. The same SqlSession but different query conditions
    3. Any addition, deletion or modification is performed during two queries of the same SqlSession
    4. The cache was manually emptied during two queries of the same SqlSession

2. Second level cache of MyBatis

  • The second-level cache is at the SqlSessionFactory level. The results of SqlSession queries created by the same SqlSessionFactory will be cached; if the same query statement is executed again, the results will be obtained from the cache
  • Conditions for enabling L2 cache
    1. In the core configuration file, set the global configuration attribute cacheEnabled="true", the default is true, no need to set
    2. Set labels in the map file
    3. The second level cache must be valid after the SqlSession is closed or committed
    4. The entity class type to which the queried data is converted must implement the serialized interface
  • Invalidation of L2 cache: Arbitrary additions, deletions and modifications performed between two queries will invalidate both L1 and L2 caches at the same time

3. L2 cache related configuration

  • The cache tag added in the mapper configuration file can set some properties
  • eviction attribute: cache recycling strategy
  • LRU (Least Recently Used) – Least Recently Used: Removes objects that have not been used for the longest time.
    • FIFO (First in First out) - First in, first out: Remove objects in the order they entered the cache.
    • SOFT - Soft Reference: Remove objects based on garbage collector state and soft reference rules.
    • WEAK - Weak References: More aggressive removal of objects based on garbage collector state and weak reference rules.
    • The default is LRU
  • flushInterval property: refresh interval, in milliseconds
  • The default is not set, that is, there is no refresh interval, the cache is only refreshed when the statement (addition, deletion and modification) is called
  • size attribute: number of references, positive integer
  • Represents how many objects the cache can store at most, too large can easily lead to memory overflow
  • readOnly property: read only, true/false
  • true: 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.
    • false: read and write the cache; will return a copy of the cached object (via serialization). This will be slower, but safe, so the default is false

4. MyBatis cache query order

  • Query the second-level cache first, because there may be data in the second-level cache that has been found by other programs, which can be used directly
  • If the second level cache is not hit, then query the first level cache
  • If the first level cache is also not hit, query the database
  • After the SqlSession is closed, the data in the first-level cache will be written to the second-level cache

5. Integrate third-party cache EHCache

5.1 Add dependencies

<!-- Mybatis EHCache integration package -->
<!-- slf4j A concrete implementation of the log facade -->

5.2 Function of each jar package

jar package nameeffect
mybatis-ehcacheIntegrator pack for Mybatis and EHCache
ehcacheEHCache core package
slf4j-apiSLF4J log facade
logback-classicA concrete implementation to support SLF4J facade interface

5.3 Create the EHCache configuration file ehcache.xml

  • The name must be ehcache.xml
<?xml version="1.0" encoding="utf-8" ?>
<ehcache xmlns:xsi=""
    <!-- disk save path -->
    <diskStore path="D:\atguigu\ehcache"/>

5.4 Set the L2 cache type

Set the second level cache type in the xxxMapper.xml file

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

5.5 Add logback log

When SLF4J exists, log4j, which is a simple log, will be invalid. At this time, we need to use the specific implementation of SLF4J logback to print the log. Create the logback configuration file logback.xml, the name is fixed and cannot be changed

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <!-- Specifies the location of the log output -->
    <appender name="STDOUT"
            <!-- Format of log output -->
            <!-- In order, they are: time, log level, thread name, class to print the log, log body content, line feed -->
            <pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
    <!-- Set the global log level. The log levels, in order, are: DEBUG,INFO,WARN,ERROR -->
    <!-- Specifying any log level will only print logs at the current level and subsequent levels. -->
    <root level="DEBUG">
        <!-- Specifies the print log appender´╝îhere by " STDOUT"Referring to the previously configured appender -->
        <appender-ref ref="STDOUT" />
    <!-- Specify local log levels according to special needs -->
    <logger name="com.atguigu.crowd.mapper" level="DEBUG"/>

5.6 EHCache configuration file description

property nameIs it necessaryeffect
maxElementsInMemoryYesMaximum number of element s to cache in memory
maxElementsOnDiskYesMaximum number of element s to cache on disk, if 0 means infinity
eternalYesSets whether cached elements never expire. If it is true, the cached data is always valid. If it is false, it will also be judged according to timeToIdleSeconds and timeToLiveSeconds
overflowToDiskYesSet whether to cache expired element s to disk when the memory buffer overflows
timeToIdleSecondsnoWhen the data cached in the EhCache is accessed for two times before and after the access time exceeds the value of the timeToIdleSeconds attribute, the data will be deleted. The default value is 0, which means the idle time is infinite.
timeToLiveSecondsnoThe valid lifetime of the cached element, the default is 0. That is, the element lifetime is infinite
diskSpoolBufferSizeMBnoDiskStore (disk cache) cache size. The default is 30MB. Each Cache should have its own buffer
diskPersistentnoWhether to enable the disk to save the data in the EhCache when the VM restarts, the default is false
diskExpiryThreadIntervalSecondsnoThe running interval of the disk cache cleaning thread, the default is 120 seconds. Every 120s, the corresponding thread will clean the data in the EhCache once
memoryStoreEvictionPolicynoWhen the memory cache reaches the maximum and a new element is added, the strategy of removing elements in the cache. The default is LRU (least recently used), optional LFU (least frequently used) and FIFO (first in, first out)

Tags: Java Mybatis Cache programming language

Posted by vh3r on Sat, 21 May 2022 22:14:55 +0300