为了实现延迟加载,对classRoom和Student的查询必须分开,分成两步来做,才能够
实现。为此,我们需要单独查询student,也就是需要在Mapper配置文件中,单独编写查询Student集合数据的SQL语句。
步骤一:首先配置StudentMapper.xml
步骤二:对classRoomMapper.xml进行配置
StudentMapper.java:
package cn.mapper;
import cn.pojo.Student;
import cn.pojo.classRoom;
import java.util.List;
public interface StudentMapper {
// 多对一情况下使用的
Student selectByName(String stuName);
//一对多时使用的方法
List selectStudentwithClassRoomTwoStep(int id);
}
classRoomMapper.java:
package cn.mapper;
import cn.pojo.classRoom;
public interface classRoomMapper {
//多对一情况下使用的
classRoom selectByclassId(int id);
//一对多情况下使用的
classRoom selectClassRoomwithTowStep(int id);
}
测试类:
@Test
public void ManyToOne() throws Exception{
//目标:在查询学生信息的同时,分步将教室信息也查询出来
StudentMapper sutdentmapper = sqlSession.getMapper(StudentMapper.class);
// 执行关联查询
Student student = sutdentmapper.selectByName("小绿");
// 打印student本身信息
System.out.println("student="+student);
// 获取关联的classRoom对象
classRoom cr = student.getClassRoom();
System.out.println("classRoom="+cr);
}
二、一对多的分步查询
步骤一:先配置classRoomMapper.xml
步骤二:配置StudentMapper.xml
StudentMapper.java:
package cn.mapper;
import cn.pojo.Student;
import cn.pojo.classRoom;
import java.util.List;
public interface StudentMapper {
// 多对一情况下使用的
Student selectByName(String stuName);
//一对多时使用的方法
List selectStudentwithClassRoomTwoStep(int id);
}
classRoomMapper.java:
package cn.mapper;
import cn.pojo.classRoom;
public interface classRoomMapper {
//多对一情况下使用的
classRoom selectByclassId(int id);
//一对多情况下使用的
classRoom selectClassRoomwithTowStep(int id);
}
测试类:
@Test
public void OneToMany() throws Exception {
//目标:在查询classroom的同时,分步将与classroom关联的student的数据页查询出来
classRoomMapper roomMapper = sqlSession.getMapper(classRoomMapper.class);
classRoom classRoom = roomMapper.selectClassRoomwithTowStep(1);
//输出classRoom被查询出来的结果
System.out.println("classRoom"+classRoom);
//输出关联的student的对象
List student = classRoom.getStudent();
for (Student student1 : student) {
System.out.println("student"+student1);
}
}
三、延迟加载
延时加载:
查询到classRoom的时候,不一定会用Student的List集合数据。如果Student的集合数据始终没有使用,那么这部分数据占用的内存就浪费了。对此,我们希望不一定会被用到数据,能过在需要使用的时候再去查询。
延迟加载的概念:对于实体类关联的属性到需要使用时才查询,也叫懒加载。
在mybatis的核心配置文件中的settings中配置,注意:mybatis小于3.4.1版本的需要两个都配置,高于3.4.1时只配第一个就行
设置为true开启懒加载功能设置为false,关闭“积极的懒加载”
开启后就可以用线程睡眠来测试
测试:使用多对一的代码测试
注意,测试延迟加载时不要打印Student对象的整体,这样没效果
@Test
public void ManyToOne() throws Exception{
//目标:在查询学生信息的同时,分步将教室信息也查询出来
StudentMapper sutdentmapper = sqlSession.getMapper(StudentMapper.class);
// 执行关联查询
Student student = sutdentmapper.selectByName("小绿");
// 打印student本身信息
// 注意测试延迟加载时不要打印Student对象的整体,这样没效果
// System.out.println("student="+student);
System.out.println("学号"+student.getSid()+"姓名"+student.getStuName());
Thread.sleep(6000);
// 获取关联的classRoom对象
classRoom cr = student.getClassRoom();
System.out.println("classRoom="+cr);
}
结果是,先执行查询查询student的sql语句,等待6秒后再执行classroom的sql语句,如图:



