一、延迟加载
1、在mybatis.xml配置文件中,开启延迟加载
2、配置mapper文件
1、一对一
* 一方
* 另一方
* 测试
Student student = smapper.selectStudentGradeById(4);
System.out.println(student);
// student.hashCode();
System.out.println(student.getGrade());
2、一对多
* 一方
* 多方
* 测试
Grade grade = gmapper.selectById(1);
System.out.println(grade);
// student.hashCode();
System.out.println(grade.getStudents());
二、缓存
1、一级缓存
1、概念
一级缓存是SqlSession范围的缓存,当调用SqlSession的修改,添加,删除,commit(),close()等方法时,就会清空一级缓存。
2、测试
// Student student1 = smapper.selectStudentGradeById(1);
// Student student2 = smapper.selectStudentGradeById(1);
// System.out.println(student1 == student2); // true
// ********************************
Student student1 = smapper.selectStudentGradeById(1);
Student student = new Student();
student.setName("杜兰特");
student.setAge(28);
student.setSex(1);
smapper.insertStudent(student);
Student student2 = smapper.selectStudentGradeById(1);
System.out.println(student1 == student2); // false
2、二级缓存
1、开启二级缓存
1、对象需要实现Serializable接口
2、在mybatis.xml配置文件中,开启二级缓存
3、配置mapper文件
2、测试
SqlSession sqlSession1 = sqlSessionFactory.openSession();
StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
Student student1 = mapper1.selectStudentGradeById(1);
sqlSession1.close();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
StudentMapper mapper2 = sqlSession2.getMapper(StudentMapper.class);
Student student2 = mapper2.selectStudentGradeById(1);
sqlSession2.close();
// 只查询了一次数据库。二级缓存存储的是数据,并不是对象
System.out.println(student1 == student2); // false
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。