1.緩存概述
緩存是一般的ORM 框架都會(huì)提供的功能,目的就是提升查詢的效率和減少數(shù)據(jù)庫的壓力,合理使用緩存是優(yōu)化中最常見的,將從數(shù)據(jù)庫中查詢出來的數(shù)據(jù)放入緩存中悦污,下次使用時(shí)不必從數(shù)據(jù)庫查詢,而是直接從緩存中讀取,避免頻繁操作數(shù)據(jù)庫螟碎,減輕數(shù)據(jù)庫的壓力,同時(shí)提高系統(tǒng)性能迹栓。
2.一級(jí)緩存
2.1 定義
一級(jí)緩存是SqlSession級(jí)別的緩存掉分。在操作數(shù)據(jù)庫時(shí)需要構(gòu)造sqlSession對(duì)象,在對(duì)象中有一個(gè)數(shù)據(jù)結(jié)構(gòu)用于存儲(chǔ)緩存數(shù)據(jù)克伊。不同的sqlSession之間的緩存數(shù)據(jù)區(qū)域是互相不影響的酥郭。也就是他只能作用在同一個(gè)sqlSession中,不同的sqlSession中的緩存是互相不能讀取的愿吹。
2.2 一級(jí)緩存的工作原理
- 用戶發(fā)起查詢請(qǐng)求不从,查找某條數(shù)據(jù),sqlSession先去緩存中查找犁跪,是否有該數(shù)據(jù)椿息,如果有,讀瓤姥堋寝优;如果沒有,從數(shù)據(jù)庫中查詢枫耳,并將查詢到的數(shù)據(jù)放入一級(jí)緩存區(qū)域乏矾,供下次查找使用。
2.3 使用一級(jí)緩存
一級(jí)緩存默認(rèn)有效,不需要任何配置妻熊,我們主要驗(yàn)證調(diào)用兩次查詢語句夸浅,實(shí)際sql執(zhí)行情況
xml配置:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mapper.UserMapper">
<select id="selectById" parameterType="int" resultType="User">
select * from user where id = #{id}
</select>
<update id="update" parameterType="User" >
update user set name=#{name} ,age=#{age} where id= #{id}
</update>
</mapper>
接口:
public interface UserMapper {
public User selectById(int id);
public void update(User user);
}
測(cè)試:
@Test
public void testMybatis(){
try {
//獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession();
//通過SqlSession創(chuàng)建UserMapper的對(duì)象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectById(11);
System.out.println(user);
User user2 = userMapper.selectById(11);
System.out.println(user2);
//提交事務(wù)
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
結(jié)果:查看如下結(jié)果,查詢兩次用戶記錄扔役,sql只執(zhí)行一次帆喇,另一次直接從session的緩存中獲取數(shù)據(jù),說明session緩存生效亿胸。
[10:55:31.437] [DEBUG] [main] [org.apache.ibatis.datasource.pooled.PooledDataSource] [Created connection 1846406218.]
[10:55:31.438] [DEBUG] [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction] [Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6e0dec4a]]
[10:55:31.444] [DEBUG] [main] [com.atguigu.mapper.UserMapper.selectById] [==> Preparing: select * from user where id = ?]
[10:55:31.480] [DEBUG] [main] [com.atguigu.mapper.UserMapper.selectById] [==> Parameters: 11(Integer)]
[10:55:31.503] [DEBUG] [main] [com.atguigu.mapper.UserMapper.selectById] [<== Total: 1]
User{id=11, name='尚硅谷', age=1}
User{id=11, name='尚硅谷', age=1}
但是有以下幾種情況,一級(jí)緩存將失效
情況1:當(dāng)關(guān)閉session時(shí)坯钦,一級(jí)緩存失效
@Test
public void testMybatisCloseSession(){
try {
//獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession();
//通過SqlSession創(chuàng)建UserMapper的對(duì)象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectById(11);
System.out.println(user);
//關(guān)閉session
sqlSession.close();
User user2 = userMapper.selectById(11);
System.out.println(user2);
//提交事務(wù)
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
情況2:當(dāng)執(zhí)行update語句時(shí),一級(jí)緩存失效
@Test
public void testMybatisUpdate() {
try {
//獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession();
//通過SqlSession創(chuàng)建UserMapper的對(duì)象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectById(11);
System.out.println(user);
//更新當(dāng)前記錄 前一次查詢的緩存失效
user.setAge(20);
userMapper.update(user);
User user2 = userMapper.selectById(11);
System.out.println(user2);
//提交事務(wù)
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
情況3:當(dāng)手動(dòng)清理緩存侈玄,一級(jí)緩存失效
@Test
public void testMybatisClearCache() {
try {
//獲取SqlSession對(duì)象
SqlSession sqlSession = sqlSessionFactory.openSession();
//通過SqlSession創(chuàng)建UserMapper的對(duì)象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectById(11);
System.out.println(user);
//清空緩存婉刀,一級(jí)緩存失效
sqlSession.clearCache();
User user2 = userMapper.selectById(11);
System.out.println(user2);
//提交事務(wù)
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
3.二級(jí)緩存
3.1 定義
二級(jí)緩存是Mybatis提供的比一級(jí)緩存范圍更大的便于開放接口的緩存,當(dāng)查詢的sql存放在一個(gè)namespace下時(shí)序仙,它們可以使用二級(jí)緩存突颊,二級(jí)緩存需要手動(dòng)開啟 ,默認(rèn)二級(jí)緩存是關(guān)閉的潘悼。
3.2 二級(jí)緩存工作原理
二級(jí)緩存是mapper級(jí)別的緩存律秃,多個(gè)SqlSession去操作同一個(gè)Mapper的sql語句,多個(gè)SqlSession可以共用二級(jí)緩存治唤,二級(jí)緩存是跨SqlSession的棒动。
UserMapper有一個(gè)二級(jí)緩存區(qū)域(按namespace分),其它mapper也有自己的二級(jí)緩存區(qū)域(按namespace分)宾添。每一個(gè)namespace的mapper都有一個(gè)二級(jí)緩存區(qū)域船惨,兩個(gè)mapper的namespace如果相同,這兩個(gè)mapper執(zhí)行sql查詢到數(shù)據(jù)將存在相同的二級(jí)緩存區(qū)域中缕陕。
3.3 使用二級(jí)緩存
在MyBatis的配置文件中加入:
在sqlconfig.xml中
<!--開啟二級(jí)緩存-->
<setting name="cacheEnabled" value="true"/>
在需要開啟二級(jí)緩存的mapper.xml中加入caceh標(biāo)簽
<cache/>
讓使用二級(jí)緩存的POJO類實(shí)現(xiàn)Serializable接口
public class User implements Serializable {}
測(cè)試
@Test
public void testCache2() throws Exception {
SqlSession sqlSession1 = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
UserMapper userMapper1 = sqlSession1.getMapper(UserMapper.class);
User user1 = userMapper1.findUserById(1);
System.out.println(user1);
sqlSession1.close();
UserMapper userMapper2 = sqlSession2.getMapper(UserMapper.class);
User user2 = userMapper2.findUserById(1);
System.out.println(user2);
sqlSession2.close();
}
輸出結(jié)果
DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 103887628.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@631330c]
DEBUG [main] - ==> Preparing: SELECT * FROM user WHERE id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
User [id=1, username=張三, sex=1, birthday=null, address=null]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@631330c]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@631330c]
DEBUG [main] - Returned connection 103887628 to pool.
DEBUG [main] - Cache Hit Ratio [com.iot.mybatis.mapper.UserMapper]: 0.5
User [id=1, username=張三, sex=1, birthday=null, address=null]
我們可以從打印的信息看出粱锐,兩個(gè)sqlSession,去查詢同一條數(shù)據(jù)榄檬,只發(fā)起一次select查詢語句卜范,第二次直接從Cache中讀取。
Spring和MyBatis整合時(shí)鹿榜, 每次查詢之后都要進(jìn)行關(guān)閉sqlSession,關(guān)閉之后數(shù)據(jù)被清空锦爵。所以spring整合之后舱殿,如果沒有事務(wù),一級(jí)緩存是沒有意義的险掀。那么如果開啟二級(jí)緩存沪袭,關(guān)閉sqlsession后,會(huì)把該sqlsession一級(jí)緩存中的數(shù)據(jù)添加到namespace的二級(jí)緩存中樟氢。這樣冈绊,緩存在sqlsession關(guān)閉之后依然存在侠鳄。
3.4 總結(jié)
對(duì)于查詢多commit少且用戶對(duì)查詢結(jié)果實(shí)時(shí)性要求不高,此時(shí)采用mybatis二級(jí)緩存技術(shù)降低數(shù)據(jù)庫訪問量死宣,提高訪問速度伟恶。
但不能濫用二級(jí)緩存,二級(jí)緩存也有很多弊端毅该,從MyBatis默認(rèn)二級(jí)緩存是關(guān)閉的就可以看出來博秫。
二級(jí)緩存是建立在同一個(gè)namespace下的,如果對(duì)表的操作查詢可能有多個(gè)namespace眶掌,那么得到的數(shù)據(jù)就是錯(cuò)誤的挡育。