This article takes you through the mybatis cache

Table of contents

Basic overview

Cache: cache

Classification

L1 cache

demo demo

 Under what circumstances does the cache not go?

L2 cache

 demo demo

 Related configuration of the second level cache


Basic overview

Cache: cache

The role of the cache: to improve the execution efficiency of the program by reducing IO. MyBatis includes a very powerful query cache feature, which can be configured and customized very easily. Caching can greatly improve query efficiency.

Classification

Two levels of cache are defined by default in the MyBatis system, namely the first level cache and the second level cache.

Basic introduction: ① By default, only the first level cache (SqlSession level cache, also known as local cache) is enabled. ② The second-level cache needs to be manually opened and configured. It is based on the namespace-level cache. ③ In order to improve scalability, MyBatis defines the cache interface Cache, and we can customize the second-level cache by implementing the Cache interface.

Caching is only for DQL statements, that is to say, the caching mechanism only corresponds to select statements.

L1 cache

Level 1 cache is enabled by default. No configuration is required.

Principle: As long as the same SQL statement is executed using the same SqlSession object, the cache will be taken.

demo demo

    public static void main(String[] args) {
        SqlSession session = SqlSessionUtil.openSession();
        StudentMapper mapper = session.getMapper(StudentMapper.class);
        //第一次查询
        List<Student> students = mapper.selectByCid(2101L);
        //第二次查询
        List<Student> students1 = mapper.selectByCid(2101L);
    }

The above code uses the same SqlSession to query the database. According to the reason, it should query the database twice, but due to the existence of the cache, it will only query the database once, as shown below

 Under what circumstances does the cache not go?

If the current first-level cache is not used, the effect is to issue a query to the database again

  • The first type: different SqlSession objects.
  • The second type: the query conditions have changed.

There are two types of first-level cache failures:

  • The first type: Between the first query and the second query, the first-level cache is manually cleared.
sqlSession.clearCache();

Note that this method only clears the first-level cache of the current session. 

  • The second type: between the first query and the second query, additions, deletions, and modifications are performed. [This addition, deletion, and modification has nothing to do with which table, as long as there is an insert delete update operation, the first-level cache will become invalid.

In fact, this is because each addition, deletion, modification, and query has the label flushCache, and the addition, deletion, and modification defaults to flushCache="true", that is, the first-level cache and the second-level cache are cleared after execution.  

L2 cache

The scope of the second level cache is SqlSessionFactory.

To use the second-level cache, the following conditions must be met:

  1. <setting name="cacheEnabled" value="true"> Globally enables or disables any cache configured in all mapper configuration files . The default is true, no need to set.
  2. Add configuration to the SqlMapper.xml file that needs to use the second-level cache: <cache />
  3. Entity class objects using the second-level cache must be serializable, that is, they must implement the java.io.Serializable interface
  4. After the SqlSession object is closed or submitted, the data in the first-level cache will be written to the second-level cache. At this time, the second level cache is available.

Data will be fetched from the second level cache. The detected data will be placed in the first-level cache by default, and the data in the first-level cache will be transferred to the second-level cache only after the session is submitted or closed.

 demo demo

@Test
public void testSelectById2() throws Exception{
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));

    SqlSession sqlSession1 = sqlSessionFactory.openSession();
    CarMapper mapper1 = sqlSession1.getMapper(CarMapper.class);
    Car car1 = mapper1.selectById(83L);
    System.out.println(car1);

    // 关键一步
    sqlSession1.close();

    SqlSession sqlSession2 = sqlSessionFactory.openSession();
    CarMapper mapper2 = sqlSession2.getMapper(CarMapper.class);
    Car car2 = mapper2.selectById(83L);
    System.out.println(car2);
}

 

 Invalidation of the second-level cache: as long as there are additions, deletions, and modifications between two queries. The second level cache will be invalidated. [Level 1 cache will also fail]

 Related configuration of the second level cache

 evictio: cache recycling strategy

    LRU - least recently used, removes objects that have not been used for the longest time.
    FIFO - first in, first out, removes objects in the order they came into the cache.
    SOFT - Soft references, remove objects based on garbage collector state and referencing rules.
    WEAK - Weak references, more aggressive removal of objects based on garbage collector state and weak reference rules. The default is LRU.

flushInterval: cache refresh interval

    How often the cache is cleared. It is not cleared by default. You can set a millisecond value.

readOnly: whether to read only

    true: read-only , MyBatis considers all operations to obtain data from the cache are read-only operations and will not modify the data, so in order to speed up, mybatis directly gives the reference of the data in the cache to the user. This way is not safe, but fast.
    false: Not read-only , MyBatis thinks that the acquired data may be modified, so MyBatis will use serialization and deserialization technology to clone a new data for you. This method is safe, but slow. Therefore, at this time, all objects that need to be stored in the second-level cache need to implement the serialization interface.

size: how many elements are stored in the cache
type: specify the full class name of the custom cache

Guess you like

Origin blog.csdn.net/m0_62436868/article/details/131813747