1.什么是缓存
缓存是存在于==内存中==的临时数据。
mysql数据库中的数据存在----表--->磁盘上。 查询---程序IO读取磁盘的数据---添加--io向磁盘添加数据。
2.缓存的好处
使用缓存减少和数据库的交互次数,提高执行效率。
3.什么样的数据适合放入缓存
经常查询并且不经常改变的;
数据的正确与否对最终结果影响不大的;
4.什么样的数据不适合放入缓存
经常改变的数据;
数据的正确与否对最终结果影响很大的;---数据安全性要求不高。
例如:商品的库存,银行的汇率,股市的牌价;
5.mybatis它也支持缓存
mybatis支持两种缓存
(1)一级缓存----基于SqlSession级别的缓存。默认一级缓存是开启的,不能关闭。
(2)二级缓存--基于SqlSessionFactory级别的缓存,它可以做到多个SqlSession共享数据。默认它是关闭。需要手动开启。
5.1 演示一级缓存
//一级缓存 ---必须查询同一个数据
@Test
public void test01() throws Exception {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
//我要是第一次查询编号=3的用户信息 --缓存不能命中,则数据库查询-发送sql语句
// 然后把查询的结果放入到缓存中
Student student = studentMapper.selectByPrimaryKey(3);
System.out.println(student);
Student student1 = studentMapper.selectByPrimaryKey(3);
System.out.println(student1);
}
//一级缓存 -- 给予sqlSession完成的一级缓存
@Test
public void test02() throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
//第一次查询编号=3的用户信息 --缓存不能命中 则想数据库查询-发送sql语句
// 把查询到的结果放到缓存中
Student student = studentMapper.selectByPrimaryKey(3);
System.out.println(student);
session.close();
//然后我在开启一个新的SqlSession
SqlSession session1 = factory.openSession();
StudentMapper studentMapper1 = session1.getMapper(StudentMapper.class);
Student student1 = studentMapper1.selectByPrimaryKey(3);
System.out.println(student1);
}
5.2.演示二级缓存
(1)开启二级缓存 mybatis中
<settings>
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
(2)在映射文件中使用二级缓存
<!--使用二级缓存 这里面的所有查询都使用了二级缓存-->
<cache/>
(3)实体一定要实现序列化接口
(4)测试二级缓存
//二级缓存的测试
@Test
public void test03() throws Exception{
Reader reader = Resources.getResourceAsReader("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = factory.openSession();
StudentMapper studentMapper = session.getMapper(StudentMapper.class);
//第一次查询编号=2的用户信息--缓存不能命中,则向数据库查询-发送sql语句、把查询的结果放入缓存中。
//底层就是一个hashmap---(2,user);
//查询的结果放入一级缓存和二级缓存。 如果二级缓存能命中
Student student = studentMapper.selectByPrimaryKey(3);
System.out.println(student);
session.close();
//然后我在开启一个新的SqlSession
SqlSession session1 = factory.openSession();
StudentMapper studentMapper1 = session1.getMapper(StudentMapper.class);
Student student1 = studentMapper1.selectByPrimaryKey(3);
System.out.println(student1);
}