This video view address: https://edu.51cto.com/sd/3ec2c
1, Cache 1.1, the meaning of the cache
The data that the user queries frequently is put in the cache (memory), the user can query the data without querying from the disk (relational database data file), querying from the cache, thus improving the query efficiency and solving the performance problem of the high concurrency system.
1.2, first-level cache
MyBatis's first-level cache scope is session, when Opensession () executes the same SQL (same statement and arguments, MyBatis does not execute SQL, but hits and returns from the cache)
MyBatis executes the query first hit in the buffer, if the hit directly return, no hit to execute SQL, query from the database
Note: MyBatis and spring after the integration of Mapper agent development, does not support the first level cache, MyBatis and spring integration, spring according to mapper template to generate Mapper proxy object, the template in the final unified close sqlsession
1.2.1, test-level caching
@Test public void testCache()throws Exception{ User user = userMapper.selectUserById(8); System.out.println(user); User user2 = userMapper.selectUserById(8); System.out.println(user2); }
Log file
DEBUG - Opening JDBC ConnectionDEBUG - Created connection 1667925979.DEBUG - Setting autocommit to false on JDBC Connection [[email protected]]DEBUG - ==> Preparing: select userid,user_name as userName,age,pwd,sex,birthday from tb_user where userid = ? DEBUG - ==> Parameters: 8(Integer)DEBUG - <== Total: 1User [userid=8, userName=hello, pwd=123456, age=18, sex=男, birthday=Tue Aug 14 10:19:19 CST 2018]User [userid=8, userName=hello, pwd=123456, age=18, sex=男, birthday=Tue Aug 14 10:19:19 CST 2018]DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]]DEBUG - Closing JDBC Connection [[email protected]]DEBUG - Returned connection 1667925979 to pool.
found that only one SQL statement was issued, and the second execution actually took the data from the cache
1.2.2, flush cache operations
Sqlsession.clearcache ();
@Test public void testCache()throws Exception{ User user = userMapper.selectUserById(8); System.out.println(user); //清除缓存 sqlSession.clearCache(); User user2 = userMapper.selectUserById(8); System.out.println(user2); }
Log file
DEBUG - Opening JDBC ConnectionDEBUG - Created connection 823632238.DEBUG - Setting autocommit to false on JDBC Connection [[email protected]]DEBUG - ==> Preparing: select userid,user_name as userName,age,pwd,sex,birthday from tb_user where userid = ? DEBUG - ==> Parameters: 8(Integer)DEBUG - <== Total: 1User [userid=8, userName=hello, pwd=123456, age=18, sex=男, birthday=Tue Aug 14 10:19:19 CST 2018]DEBUG - ==> Preparing: select userid,user_name as userName,age,pwd,sex,birthday from tb_user where userid = ? DEBUG - ==> Parameters: 8(Integer)DEBUG - <== Total: 1User [userid=8, userName=hello, pwd=123456, age=18, sex=男, birthday=Tue Aug 14 10:19:19 CST 2018]DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]]DEBUG - Closing JDBC Connection [[email protected]]DEBUG - Returned connection 823632238 to pool.
An update operation was performed
@Test public void testCache()throws Exception{ User user = userMapper.selectUserById(8); System.out.println(user); user.setUserName("李白"); userMapper.insertUser(user); sqlSession.commit(); User user2 = userMapper.selectUserById(8); System.out.println(user2); }
Log file
debug-opening jdbc connectiondebug-created connection 1782252248.debug-setting autocommit to false on JDBC Connectio n [[Email protected]]debug-==> preparing:select userid,user_name as Username,age,pwd,sex,birthday from Tb_use r where UserID =? Debug-==> parameters:8 (Integer) Debug-<== Total:1user [Userid=8, Username=hello, pwd=123456, age=18, sex= Male , Birthday=tue 10:19:19 CST 2018]debug-==> preparing:insert into Tb_user (USERID,USER_NAME,AGE,PWD,SEX,BIRTHD ay) VALUES (seq_user.nextval,?,?,?,?,?) Debug-==> Parameters: Li Bai (string), (Integer), 123456 (String), male (string), 2018-08-14 10:19:19.0 (Timestamp) DEBUG-&L t;== updates:1debug-committing JDBC Connection [[Email protected]]debug-==> Preparing:select Userid,user _name as Username,age,pwd,sex,birthday from tb_user where UserID =? Debug-==> parameters:8 (Integer) Debug-<== Total:1user [Userid=8, Username=hello, pwd=123456, age=18, sex= Male , Birthday=tue 14 10:19:19 CST 2018]debug-resetting autocommit to True on JDBC Connection [[email protected]]debug-closing jdbc Co nnection [[email protected]]debug-returned Connection 1782252248 to pool.
1.3, Level Two cache
The scope of the MyBatis level two cache is a mapper namespace, and the query SQL in the same namespace can be hit from the cache
Each query first to see whether to turn on level two cache, if you turn on the data structure from the level two cache to fetch the cached data,
The second-level cache is scoped to the mapper level (mapper the same namespace), Mapper creates the cached data structure in the namespace, Map<key, value>.
If it is not taken from the level two cache, then it is found from the first level cache, and if there is no cache, query from the database
1.3.1, Level two cache
MyBatis level Two cache requires the Pojo implementation of the query result map java.io.serializable interface, and throws an exception if not implemented
The secondary cache can write memory data to disk, there is serialization and deserialization of the object, so implement the Java.io.serializable interface.
If the pojo of the result map also includes Pojo, implement the Java.io.serializable interface.
1.3.2, turn on level two cache
Turn on global switch (mybatis-config.xml)
<settings> <setting name="mapUnderscoreToCamelCase" value="false"/> <!-- 二级缓存的全局开关 --> <setting name="cacheEnabled" value="true"/></settings>
Turn on the local switch
<mapper namespace="cn.org.kingdom.mapper.UserMapper"> <cache/> ...</mapper>
1.3.3, Test level two cache
@Test public void testCache2()throws Exception{ User user = userMapper.selectUserById(8); System.out.println(user); sqlSession.close(); sqlSession = sqlSessionFactory.openSession(); userMapper = sqlSession.getMapper(UserMapper.class); User user2 = userMapper.selectUserById(8); System.out.println(user2); }
Log file
DEBUG - Checking to see if class cn.org.kingdom.mapper.UserMapper matches criteria [is assignable to Object]DEBUG - Cache Hit Ratio [cn.org.kingdom.mapper.UserMapper]: 0.0DEBUG - Opening JDBC ConnectionDEBUG - Created connection 221388699.DEBUG - Setting autocommit to false on JDBC Connection [[email protected]]DEBUG - ==> Preparing: select userid,user_name as userName,age,pwd,sex,birthday from tb_user where userid = ? DEBUG - ==> Parameters: 8(Integer)DEBUG - <== Total: 1User [userid=8, userName=hello, pwd=123456, age=18, sex=男, birthday=Tue Aug 14 10:19:19 CST 2018]DEBUG - Resetting autocommit to true on JDBC Connection [[email protected]]DEBUG - Closing JDBC Connection [[email protected]]DEBUG - Returned connection 221388699 to pool.DEBUG - Cache Hit Ratio [cn.org.kingdom.mapper.UserMapper]: 0.5User [userid=8, userName=hello, pwd=123456, age=18, sex=男, birthday=Tue Aug 14 10:19:19 CST 2018]
1.3.4, refreshing the cache
Refreshes the level two cache (global emptying) if the sqlsession operation commits. Sets whether the statement Flushcache refreshes the cache, and the default value is true.
Test class
@Test public void testCache2()throws Exception{ //查询 User user = userMapper.selectUserById(8); System.out.println(user); sqlSession.close(); //更新操作 user.setUserName("小乔"); SqlSession session2 = sqlSessionFactory.openSession(); UserMapper userMapper3 = session2.getMapper(UserMapper.class); userMapper3.updateUser(user); session2.commit(); //再次查询 sqlSession = sqlSessionFactory.openSession(); userMapper = sqlSession.getMapper(UserMapper.class); User user2 = userMapper.selectUserById(8); System.out.println(user2); }
In Mapper.xml
<update id="updateUser" flushCache="false"> update tb_user set user_name=#{userName},age=#{age},pwd=#{pwd},sex=#{sex},birthday=#{birthday} where userid=#{userid}</update>
Log
debug-created connection 876236253.debug-setting autocommit to False on JDBC connection [[Email protected]]debug -==> Preparing:select Userid,user_name as Username,age,pwd,sex,birthday from tb_user where UserID =? Debug-==> parameters:8 (Integer) Debug-<== Total:1user [Userid=8, Username= frozen Ares, pwd=123456, age=18, sex= Male, Birthday=tue 10:19:19 CST 2018]debug-resetting autocommit to True on JDBC Connection [[Email protected]]deb ug-closing JDBC Connection [[email protected]]debug-returned Connection 876236253 to pool. Debug-opening JDBC connectiondebug-checked out connection 876236253 from pool. Debug-setting autocommit to False on JDBC Connection [[Email protected]]debug-==> preparing:update tb_user s ET user_name=?,age=?,pwd=?,sex=?,birthday=? where userid=? DEBUG-==> Parameters: Joe Cole (String), (Integer), 123456 (String), male (string), 2018-08-14 10:19:19.0 (Timestamp), 8 ( Integer) DEBUG-<== Updates:1debug-committing JDBC Connection [[Email protected]]debug-cache hit Ratio [cn.org.kingdom.mapper.UserMapper]: 0.5User [ Userid=8, Username= frozen Ares, pwd=123456, age=18, sex= Male, Birthday=tue-10:19:19 CST 2018]
For cache use, generally, the data that we want to use frequently, the data does not change too much, or has no effect on the user
Advanced settings for 1.3.5, caching
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
This more advanced configuration creates a FIFO cache, refreshes every 60 seconds, saves 512 references to the resulting object or list, and the returned objects are considered read-only, so modifying them between callers in different threads can cause conflicts.
The available retract policies are:
LRU
– Least Recently used: Removes objects that are not used for the longest time.
FIFO
– FIFO: Removes them by the order in which the objects enter the cache.
SOFT
– Soft Reference: Removes objects based on the garbage collector state and soft reference rules.
WEAK
– Weak references: More aggressively remove objects based on the garbage collector state and weak reference rules.
The default is LRU.
The Flushinterval (refresh interval) can be set to any positive integer, and they represent a reasonable millisecond in the form of a time period. The default is not set, that is, there is no refresh interval, and the cache simply refreshes when the statement is invoked.
The size (number of references) can be set to any positive integer, keeping in mind the number of objects you cache and the number of available memory resources for the environment you are running. The default value is 1024.
The readOnly (read-only) property can be set to TRUE or false. A read-only cache returns the same instance of the cached object to all callers. Therefore, these objects cannot be modified. This provides a very important performance advantage. A read-write cache returns a copy of the cached object (by serialization). This will be slower, but safe, so the default is false.
Finally, please pay attention to my online classroom: https://edu.51cto.com/sd/ef353
MyBatis Learning (6)