In depth understanding of Mybatis level 2 caching

  • 2020-05-24 05:40:14
  • OfStack

The last article introduced mybatis1 level cache to you, you can refer to the need of friends.

Compared with level 1 cache, level 2 cache has a larger range and can be Shared by multiple SqlSession.

If the same query is sent, sql will first look in the cache and then query the database if it cannot be found.

Each namespace mapper has its own cache space.

If both mapper's namespace are the same, the data queried by executing mapper will be stored in the same level 2 cache.

Also if you have sqlSession executed commit will clear the level 2 cache.

Configuration file (no configuration is also enabled by default):

In sqlMapConfig. xml in:


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

In the corresponding mapper.xml:

<cache/>

If level 2 caching is not required, you can disable level 2 caching in Settings


<select useCache="false"></select>

So you're reading from the database every time

After executing insert,update,delete, the cache will be refreshed (the cache will be cleared), which can be set not to refresh

1 general not set, setting may cause dirty read.


<insert flushCache="false"></insert>

Example:


SqlSession session1 = factory.openSession();
   SqlSession session2 = factory.openSession();
   SqlSession session3 = factory.openSession();
   UserMapper mapper1 = session1.getMapper(UserMapper.class);
   UserMapper mapper2 = session2.getMapper(UserMapper.class);
   UserMapper mapper3 = session3.getMapper(UserMapper.class);
   // The first 1 Time request , The query id for 1 The user 
   User user1 = mapper1.findUserById(1);
   System.out.println(user1);
   //close  Write data 2 Level cache 
   session1.close();
   // empty 2 Level cache ,UserMapper Under the 
   user1.setUsername("mmm");
   mapper3.updateUser(user1);
   session3.commit();
   // The first 2 The secondary query will be found in the cache 
   User user2 = mapper2.findUserById(1);
   System.out.println(user2);
   session2.close();

Note that the objects to be cached at level 2 here must implement the Serilizable interface because the cached data may be deserialized to the hard disk or elsewhere.


Related articles: