马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
优质博文:IT-BLOG-CN
一、一级缓存设置
MyBatis一级缓存默认是开启的。假如必要表现的开启,必要在MyBaits设置文件中<settings>标签中添加如下语句:
- <settings>
- <setting name="localCacheScope" value="SESSION"/>
- </settings>
复制代码 value共有两个选项,SESSION大概STATEMENT,默认是SESSION级别,即在一个MyBatis会话中实验的全部语句,都会共享这一个缓存。一种是STATEMENT级别,可以明白为缓存只对当前实验的这一个Statement有用。
一级缓存基于SqlSession举个例子:
- public void getStudentById() throws Exception {
-
-
- SqlSession sqlSession = factory.openSession(true); // 自动提交事务
- StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
- System.out.println(studentMapper.getStudentById(1));
- System.out.println(studentMapper.getStudentById(1));
- }
复制代码 实验结果:我们可以看到,只有第一次真正查询了数据库,后续的查询使用了一级缓存。
- DEBUG [main] - ==> Preparing: SELECT id,name,age FROM student WHERE id = ?
- DEBUG [main] - ==> Parameters: 1(Integer)
- TRACE [main] - <== Columns: id, name, age
- TRACE [main] - <== Row: 1, 小明, 13
- DEBUG [main] - <== Total: 1
- StudentEntity{id=1, name='小明', age=13}
- StudentEntity{id=1, name='小明', age=13}
复制代码 二、一级缓存可重复读征象
两个SqlSession利用当前行,一级缓存的可重复读案例。详细在sqlSession1中查询数据,使一级缓存见效,在sqlSession2中更新数据库,验证一级缓存只在数据库会话内部共享。
- @Test
- public void testLocalCacheScope() throws Exception {
-
-
- SqlSession sqlSession1 = factory.openSession(true);
- SqlSession sqlSession2 = factory.openSession(true);
-
- StudentMapper studentMapper = sqlSession1.getMapper(StudentMapper.class);
- StudentMapper studentMapper2 = sqlSession2.getMapper(StudentMapper.class);
-
- System.out.println(studentMapper.getStudentById(1));
- System.out.println("更新了" + studentMapper2.updateStudentName("小花",1) + "名学生的数据");
- System.out.println(studentMapper.getStudentById(1));
- System.out.println(studentMapper2.getStudentById(1));
- }
复制代码 sqlSession2更新了id为1的弟子的姓名,从小明改为了小花,但session1
|