The client sends the same SQL query statement to the database server. If you access the database every time, it will lead to a degradation of performance.
So how to improve?
mybatis provides us with a strategy for level 1 cache
Between opening and closing of an sqlSession, the sqlSession object (actually an Executor) will maintain a cached object. When querying data, first look for whether the data exists from the cache, and if it exists, it will be retrieved directly. If it does not exist, send an sql query to the database, and then store the queryed data into the cache and return it to the program.
This will have a problem:
If a program changes the data of the database to be checked during the first and second query, it will cause the read data to be wrong, that is,
Dirty reading is actually mybatis will clear the cache after executing the commit() method in SQLSession. The second time I go to query, I will still query from the database.
You can also manually call the clearCache() method of sqlSession to clear the cache
Small examples:
@Test public void testCacheLever1() throws Exception{ SqlSession session = factory.openSession(); UserMapper mapper = session.getMapper(UserMapper.class); //The first request is to query the user with id 1 User user = mapper.findUserById(1); System.out.println(user); //Change data, the cache will be cleared user.setUsername("yyyy"); mapper.updateUser(user); session.commit(); //The second query will look for User user2 = mapper.findUserById(1); System.out.println(user2); session.close(); }question:
If sqlSession is closed, the cache will be cleared. How do you use cache to improve efficiency?
Okay, the next article introduces mybatis level 2 cache to you.
The above is the Mybatis first-level cache introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!