一级缓存
一级缓存:同一个SqlSession对象使用
Mybatis默认开启一级缓存,当第一次使用SqlSeesion对象查询数据的时候,就向数据库发送该SQL语句,并将结果放入SqlSession中,后续再使用该SqlSession查询的时候,直接从缓存中取出。
二级缓存
Reader read = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlsession = new SqlSessionFactoryBuilder().build(read);
SqlSession session = sqlsession.openSession();
StudentMapper studentmapper = session.getMapper(StudentMapper.class);
(1)、SqlSessionFactory对象产生依赖config.xml文件
(2)、SqlSession对象产生依赖SqlSessionFactory对象
(3)、xxxMapper对象依赖SqlSession对象中的(xxxMapper.class)类
结论:当使用同一个xxxMapper.class类产生xxxMapper对象,则这些对象共享二级缓存
使用二级缓存
1、在conf.xml文件中设置二级缓存
<settings>
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
</settings>
2、在该namespace下使用二级缓存
<?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">
<!-- namespace:该mapper.xml的唯一标识符-->
<mapper namespace="com.mybatis.mapper.StudentMapper">
<!--在该namespace下使用二级缓存-->
<cache/>
</mapper>
3、对进行二级缓存的对象进行序列化(implements Serializable)
序列化:内存->硬盘
反序列化:硬盘->内存
package com.mybatis.test;
import java.io.Serializable;
public class Student implements Serializable{
}
4、二级缓存测试
public static void cachequery() throws IOException {
Reader read = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlsession = new SqlSessionFactoryBuilder().build(read);
SqlSession session = sqlsession.openSession();
//
// String statement = "com.mybatis.test.studentMapper.studentSelect";
// Student stu = session.selectOne(statement, 1);
StudentMapper studentmapper = session.getMapper(StudentMapper.class);
Student stud = studentmapper.studentSelect(1);
System.out.println(stud);
session.close();
SqlSession session2 = sqlsession.openSession();
StudentMapper studentmapper2 = session2.getMapper(StudentMapper.class);
Student stud2 = studentmapper2.studentSelect(1);
System.out.println(stud2);
session2.close();
}