In depth understanding of Mybatis level 1 caching

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

The client sends the same sql query to the database server, which can result in performance degradation if the database is accessed every time.

So how do you improve it?

mybatis provides us with a level 1 caching policy

Between the open and close a sqlSession sqlSession object inside (is actually Executor) will maintain a cached object, when querying data, data from the cache to find whether there is this, the first is out directly, does not exist, send sql query to the database, then after the search of the data stored in the cache, and return to the program.

There is a problem with this:

If during the first and second query, a program changes the data of the database to be consulted, it will cause the data read to be wrong, that is

Dirty read, mybatis actually clears the cache after sqlSession executes commit(). The second time to query, will still query from the database.

You can also manually call sqlSession's clearCache() method to clear the cache

Example:


@Test
  public void testCacheLever1() throws Exception{
    SqlSession session = factory.openSession();
    UserMapper mapper = session.getMapper(UserMapper.class);
    // The first 1 Time request , The query id for 1 The user 
    User user = mapper.findUserById(1);
    System.out.println(user);
    // Change the data , It will clear the cache 
    user.setUsername("yyyy");
    mapper.updateUser(user);
    session.commit();
    // The first 2 The secondary query will be found in the cache 
    User user2 = mapper.findUserById(1);
    System.out.println(user2);
    session.close();
  }

Question:

If sqlSession is turned off, the cache is cleared. How does this use caching to improve efficiency?

Ok, the next article will introduce you to mybatis level 2 caching.


Related articles: