Employee
類html
public class Employee { private Integer id; private String lastName; private String email; private String gender; private Department dept; // 省略setter、getter、toString方法 }
Department
類java
public class Department { private Integer id; private String departmentName; private List<Employee> emps; }
再來看EmployeeMapper.xml
中的相關語句sql
<!-- 使用association進行分步查詢: 一、先按照員工id查詢員工信息 二、根據查詢員工信息中的d_id值去部門表查出部門信息 三、部門設置到員工中; --> <!-- id last_name email gender d_id --> <resultMap type="com.mybatis.bean.Employee" id="MyEmpByStep"> <id column="id" property="id"/> <result column="last_name" property="lastName"/> <result column="email" property="email"/> <result column="gender" property="gender"/> <!-- association定義關聯對象的封裝規則 select:代表當前屬性是調用select指定的方法查出的結果 column:指定將哪一列的值傳給這個方法 流程:使用select指定的方法(傳入column指定的這列參數的值)查出對象,並封裝給property指定的屬性 --> <association property="dept" select="com.mybatis.dao.DepartmentMapper.getDeptById" column="d_id"> </association> </resultMap> <!-- public Employee getEmpByIdStep(Integer id);--> <select id="getEmpByIdStep" resultMap="MyEmpByStep"> select * from tbl_employee where id=#{id} </select>
DepartmentMapper.xml
中的相關語句mybatis
<!--public Department getDeptById(Integer id); --> <select id="getDeptById" resultType="com.mybatis.bean.Department"> select id,dept_name departmentName from tbl_dept where id=#{id} </select>
經過association實現了分步查詢,在必定程度上簡化了sql語句,另外association
還指支持延遲加載(懶加載),目前的狀況是當咱們執行了getEmpByIdStep
語句,也必定執行DepartmentMapper.xml
中的getDeptById
語句,但若是並不須要部門表中的信息呢?app
如:code
Employee employee = mapper.getEmpByIdStep(3); System.out.println(employee);
查詢id
爲3的員工的信息,此時咱們並不須要部門表的信息,那能夠用懶加載的方式進行。xml
須要在mybatis全局配置文件mybatis-config.xml
中開啓htm
<settings> <!-- <setting name="mapUnderscoreToCamelCase" value="true"/> --> <setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="false"/> </settings>
對於這兩個屬性,咱們來看一下mybatis官方文檔中的介紹對象
當這樣設置後,當咱們再次運行blog
Employee employee = mapper.getEmpByIdStep(3); System.out.println(employee);
經過控制檯的打印sql語句能夠發現,並未執行查詢部門的sql語句
Employee employee = mapper.getEmpByIdStep(3); System.out.println(employee.getDept());
當這樣調用時,就會調用查詢部門的語句,實現了按需加載。