MySQL如何分步查询_mybatis使用associaton进行分步查询

Employee类

public class Employee {

private Integer id;

private String lastName;

private String email;

private String gender;

private Department dept;

// 省略setter、getter、toString方法

}

Department类

public class Department {

private Integer id;

private String departmentName;

private List emps;

}

再来看EmployeeMapper.xml中的相关语句

select="com.mybatis.dao.DepartmentMapper.getDeptById"

column="d_id">

select * from tbl_employee where id=#{id}

DepartmentMapper.xml中的相关语句

select id,dept_name departmentName from tbl_dept where id=#{id}

通过association实现了分步查询,在一定程度上简化了sql语句,另外association还指支持延迟加载(懒加载),目前的情况是当我们执行了getEmpByIdStep语句,也一定执行DepartmentMapper.xml中的getDeptById语句,但如果并不需要部门表中的信息呢?

如:

Employee employee = mapper.getEmpByIdStep(3);

System.out.println(employee);

查询id为3的员工的信息,此时我们并不需要部门表的信息,那可以用懒加载的方式进行。

需要在mybatis全局配置文件mybatis-config.xml中开启

对于这两个属性,我们来看一下mybatis官方文档中的介绍

当这样设置后,当我们再次运行

Employee employee = mapper.getEmpByIdStep(3);

System.out.println(employee);

通过控制台的打印sql语句可以发现,并未执行查询部门的sql语句

Employee employee = mapper.getEmpByIdStep(3);

System.out.println(employee.getDept());

当这样调用时,就会调用查询部门的语句,实现了按需加载。

Employee类 public class Employee { private Integer id; private String lastName; private String email; private String gender; private Department dept; // 省略setter、getter、toString方法 } Department类 public class Department { private Integer id; private String departmentName; private List emps; } 再来看EmployeeMapper.xml中的相关语句 select="com.mybatis.dao.DepartmentMapper.getDeptById" column="d_id"> select * from tbl_employee where id=#{id} DepartmentMapper.xml中的相关语句 select id,dept_name departmentName from tbl_dept where id=#{id} 通过association实现了分步查询,在一定程度上简化了sql语句,另外association还指支持延迟加载(懒加载),目前的情况是当我们执行了getEmpByIdStep语句,也一定执行DepartmentMapper.xml中的getDeptById语句,但如果并不需要部门表中的信息呢? 如: Employee employee = mapper.getEmpByIdStep(3); System.out.println(employee); 查询id为3的员工的信息,此时我们并不需要部门表的信息,那可以用懒加载的方式进行。 需要在mybatis全局配置文件mybatis-config.xml中开启 对于这两个属性,我们来看一下mybatis官方文档中的介绍 当这样设置后,当我们再次运行 Employee employee = mapper.getEmpByIdStep(3); System.out.println(employee); 通过控制台的打印sql语句可以发现,并未执行查询部门的sql语句 Employee employee = mapper.getEmpByIdStep(3); System.out.println(employee.getDept()); 当这样调用时,就会调用查询部门的语句,实现了按需加载。
经验分享 程序员 微信小程序 职场和发展