MyBatis 一级缓存原理

[复制链接]
发表于 2026-1-29 06:29:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
优质博文:IT-BLOG-CN
一、一级缓存设置

MyBatis一级缓存默认是开启的。假如必要表现的开启,必要在MyBaits设置文件中<settings>标签中添加如下语句:
  1. <settings>
  2.         <setting name="localCacheScope" value="SESSION"/>
  3. </settings>
复制代码
value共有两个选项,SESSION大概STATEMENT,默认是SESSION级别,即在一个MyBatis会话中实验的全部语句,都会共享这一个缓存。一种是STATEMENT级别,可以明白为缓存只对当前实验的这一个Statement有用。
一级缓存基于SqlSession举个例子:
  1. public void getStudentById() throws Exception {
  2.    
  3.    
  4.     SqlSession sqlSession = factory.openSession(true); // 自动提交事务
  5.     StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
  6.     System.out.println(studentMapper.getStudentById(1));
  7.     System.out.println(studentMapper.getStudentById(1));
  8. }
复制代码
实验结果:我们可以看到,只有第一次真正查询了数据库,后续的查询使用了一级缓存。
  1. DEBUG [main] - ==>  Preparing: SELECT id,name,age FROM student WHERE id = ?
  2. DEBUG [main] - ==> Parameters: 1(Integer)
  3. TRACE [main] - <==    Columns: id, name, age
  4. TRACE [main] - <==        Row: 1, 小明, 13
  5. DEBUG [main] - <==      Total: 1
  6. StudentEntity{id=1, name='小明', age=13}
  7. StudentEntity{id=1, name='小明', age=13}
复制代码
二、一级缓存可重复读征象

两个SqlSession利用当前行,一级缓存的可重复读案例。详细在sqlSession1中查询数据,使一级缓存见效,在sqlSession2中更新数据库,验证一级缓存只在数据库会话内部共享。
  1. @Test
  2. public void testLocalCacheScope() throws Exception {
  3.    
  4.    
  5.         SqlSession sqlSession1 = factory.openSession(true);
  6.         SqlSession sqlSession2 = factory.openSession(true);
  7.        
  8.         StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class);
  9.         StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class);
  10.        
  11.         System.out.println(studentMapper.getStudentById(1));
  12.         System.out.println("更新了" + studentMapper2.updateStudentName("小花",1) + "名学生的数据");
  13.         System.out.println(studentMapper.getStudentById(1));
  14.         System.out.println(studentMapper2.getStudentById(1));
  15. }
复制代码
sqlSession2更新了id为1的弟子的姓名,从小明改为了小花,但session1
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表