The client sends the same SQL query to the database server, and if it accesses the database every time, it can cause performance degradation.
So how to improve it?
MyBatis provides us with a first-level caching strategy
In a sqlsession between open and close, the Sqlsession object (in fact, executor) will maintain a cached object, when querying the data, first look for the existence of the data from the cache, there is directly out, does not exist, to the database to send SQL query, The data after the query is then cached and returned to the program.
There is a problem:
If a program changes the data of the database to be queried during the first and second queries, it will cause the read data to be wrong.
Dirty reads, in fact, mybatis the cache after sqlsession executes the commit () method. The second time you go to the query, you will still be querying from the database.
You can also manually call the Sqlsession ClearCache () method to clear the cache
Small example:
@Test public
void TestCacheLever1 () throws exception{
sqlsession session = Factory.opensession ();
Usermapper mapper = Session.getmapper (usermapper.class);
First request, the user with Query id 1
= Mapper.finduserbyid (1);
SYSTEM.OUT.PRINTLN (user);
Changing the data will empty the cache
user.setusername ("yyyy");
Mapper.updateuser (user);
Session.commit ();
The second query will look for
User user2 = Mapper.finduserbyid (1) from the cache;
System.out.println (user2);
Session.close ();
}
Problem:
If the sqlsession is closed, the cache is emptied. How does this use caching to improve efficiency?
OK, the next article will introduce you to MyBatis level two cache.
The above is a small series to introduce the MyBatis cache, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!