mybatis中resultMap用法及懶加載

本章節主要介紹mybatis的resultMap的用法,包含了級聯查詢、關聯查詢、懶加載、鑑別器的相關講解和代碼用例

 

首先這是測試代碼用到的實體類POJO

Employee.java:

package com.wcg.mybatis.entity;

import java.io.Serializable;

/**
 * @author wcg
 * @create 2019-05-06 10:04
 */
public class Employee implements Serializable {
    private static final long serialVersionUID = -6248806586248836314L;
    private Integer id;
    private String lastName;
    private String gender;
    private String email;
    private Department department;

    public Employee() {
    }
    // setting getting 省略
    
    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                ", department=" + department +
                '}';
    }
}

Department.java

package com.wcg.mybatis.entity;

import java.io.Serializable;
import java.util.List;

/**
 * @author wcg
 * @create 2019-05-07 23:59
 */
public class Department implements Serializable {

    private static final long serialVersionUID = -6380361622841645277L;
    private Integer id;
    private String deptName;
    private List<Employee> employeeList;

    public Department() {
    }

    // setting getting 省略

    @Override
    public String toString() {
        return "Department{" +
                "id=" + id +
                ", deptName='" + deptName + '\'' +
                ", employeeList=" + employeeList +
                '}';
    }
}

數據庫的建表語句DDL:

CREATE TABLE `tbl_employee` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(255) DEFAULT NULL,
  `gender` char(1) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `dept_id` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;


CREATE TABLE `tbl_department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;


一、自定義結果集映射resultMap

EmployeeMapper.java 接口:

package com.wcg.mybatis.dao;

import com.wcg.mybatis.entity.Employee;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

/**
 * @author wcg
 * @create 2019-05-06 17:48
 */
public interface EmployeeMapperPlus {

    Employee getEmpById(Integer id);

}

EmployeeMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.EmployeeMapperPlus">
	<!--
		自定義某個javaBean的封裝規則
			type:自定義規則的Java類型
			id:唯一id方便引用
	  -->
	<resultMap id="employee" type="com.wcg.mybatis.entity.Employee">
		<!--
			指定主鍵列:
				id定義主鍵會底層有優化;
				column:字段
				property:JavaBean屬性
		-->
		<id column="id" property="id"></id>
		<!-- 定義普通列封裝規則 -->
		<result column="last_name" property="lastName"></result>
		<!-- 其他不指定的列會自動封裝:我們只要寫resultMap就把全部的映射規則都寫上。 -->
		<result column="gender" property="gender"></result>
		<result column="email" property="email"></result>
	</resultMap>

	<!-- resultMap:自定義結果集映射規則;  -->
	<!-- Employee getEmpById(Integer id); -->
	<select id="getEmpById" resultMap="employee">
		select id,last_name,email,gender from tbl_employee where id = #{id}
	</select>

</mapper>

測試代碼:

package com.wcg.mybatis.test;

import com.wcg.mybatis.dao.EmployeeMapperPlus;
import com.wcg.mybatis.entity.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.InputStream;

/**
 * @author wcg
 * @create 2019-05-08 21:55
 */
public class ResultMapTest {
    public SqlSessionFactory sessionFactory = null;
    @BeforeEach
    public void test()throws Exception{
        // 根據全局配置文件(xml)創建一個SqlSessionFactory對象
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void resultMapTest(){
        // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
        SqlSession sqlSession = null;
        try {
            sqlSession = sessionFactory.openSession();
            // 通過獲取接口代理對象來執行sql語句
            EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
            Employee employee = mapper.getEmpById(2);
            System.out.println(employee);
        } finally {
            // 資源關閉,放在finally中確保一定會執行
            sqlSession.close();
        }
    }

}

測試結果:

DEBUG 05-08 22:43:39,908 ==>  Preparing: select id,last_name,email,gender from tbl_employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 22:43:39,989 ==> Parameters: 2(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 22:43:40,022 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=null}

二、級聯屬性封裝結果集

EmployeeMapper.java 接口方法:

Employee getEmpByIdWithDeptName(Integer id);

EmployeeMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.EmployeeMapperPlus">
	<!--
		聯合查詢:級聯屬性封裝結果集
	  -->
	<resultMap id="employeeWithDeptName" type="com.wcg.mybatis.entity.Employee">
		<id column="eid" property="id"></id>
		<result column="last_name" property="lastName"></result>
		<result column="gender" property="gender"></result>
		<result column="email" property="email"></result>
		<result column="did" property="department.id"></result>
		<result column="dept_name" property="department.deptName"></result>
	</resultMap>

	<select id="getEmpByIdWithDeptName" resultMap="employeeWithDeptName">
		select
			e.id as eid, e.last_name, e.email, e.gender,
			d.id as did, d.dept_name
		from
			tbl_employee e
		LEFT JOIN
			tbl_department d on e.dept_id = d.id
		where e.id = #{id}
	</select>

</mapper>

測試代碼:

@Test
    public void resultMapTest(){
        // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
        SqlSession sqlSession = null;
        try {
            sqlSession = sessionFactory.openSession();
            // 通過獲取接口代理對象來執行sql語句
            EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
            Employee employee = mapper.getEmpById(2);
            System.out.println(employee);
        } finally {
            // 資源關閉,放在finally中確保一定會執行
            sqlSession.close();
        }
    }

測試結果:

DEBUG 05-08 22:51:26,592 ==>  Preparing: select e.id as eid, e.last_name, e.email, e.gender, d.id as did, d.dept_name from tbl_employee e LEFT JOIN tbl_department d on e.dept_id = d.id where e.id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 22:51:26,676 ==> Parameters: 2(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 22:51:26,700 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=Department{id=1, deptName='開發部', employeeList=null}}

 

三、association定義關聯對象封裝結果集

(一)、普通查詢

EmployeeMapper.java 接口方法:

Employee getByIdWithDept(Integer id);

EmployeeMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.EmployeeMapperPlus">
    <!--
		使用association定義關聯的單個對象的封裝規則;
	 -->
	<resultMap id="employeeWithDept" type="com.wcg.mybatis.entity.Employee">
		<id column="eid" property="id"></id>
		<result column="last_name" property="lastName"></result>
		<result column="gender" property="gender"></result>
		<result column="email" property="email"></result>
		<!--  
			association可以指定聯合的javaBean對象
				property="dept":指定哪個屬性是聯合的對象
				javaType:指定這個屬性對象的類型[不能省略]
		-->
		<association property="department" javaType="com.wcg.mybatis.entity.Department">
			<id column="did" property="id"></id>
			<result column="dept_name" property="deptName"></result>
		</association>
	</resultMap>

	<select id="getByIdWithDept" resultMap="employeeWithDept">
		select
			e.id as eid, e.last_name, e.email, e.gender,
			d.id as did, d.dept_name
		from
			tbl_employee e
		LEFT JOIN
			tbl_department d on e.dept_id = d.id
		where e.id = #{id}
	</select>

</mapper>

測試代碼:

@Test
public void associationTest(){
    // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
    SqlSession sqlSession = null;
    try {
        sqlSession = sessionFactory.openSession();
        // 通過獲取接口代理對象來執行sql語句
        EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
        Employee employee = mapper.getByIdWithDept(2);
        System.out.println(employee);
    } finally {
        // 資源關閉,放在finally中確保一定會執行
        sqlSession.close();
    }
}

測試結果:

DEBUG 05-08 23:01:10,678 ==>  Preparing: select e.id as eid, e.last_name, e.email, e.gender, d.id as did, d.dept_name from tbl_employee e LEFT JOIN tbl_department d on e.dept_id = d.id where e.id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:01:10,746 ==> Parameters: 2(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:01:10,763 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=Department{id=1, deptName='開發部', employeeList=null}}

(二)、分步查詢

EmployeeMapper.java 接口方法:

Employee getByIdWithDeptStep(Integer id);

EmployeeMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.EmployeeMapperPlus">
    <!--
		使用association進行分步查詢:
            1、先按照員工id查詢員工信息
            2、根據查詢員工信息中的d_id值去部門表查出部門信息
            3、部門設置到員工中;
	 -->
	<resultMap id="employeeWithDeptStep" type="com.wcg.mybatis.entity.Employee">
		<id column="id" property="id"></id>
		<result column="last_name" property="lastName"></result>
		<result column="gender" property="gender"></result>
		<result column="email" property="email"></result>
		<!-- association定義關聯對象的封裝規則
	 		select:表明當前屬性是調用select指定的方法查出的結果
	 		column:指定將哪一列的值傳給這個方法 注:如果多列情況使用{key=value...}的形式
	 		流程:使用select指定的方法(傳入column指定的這列參數的值)查出對象,並封裝給property指定的屬性
	 	 -->
		<association property="department"
					 select="com.wcg.mybatis.dao.DepartmentMapper.getById"
					 column="dept_id">
		</association>
	</resultMap>

	<select id="getByIdWithDeptStep" resultMap="employeeWithDeptStep">
		select id,last_name,email,gender, dept_id from tbl_employee where id = #{id}
	</select>

</mapper>

DepartmentMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.DepartmentMapper">

	<resultMap id="department" type="com.wcg.mybatis.entity.Department">
		<id column="did" property="id"></id>
		<result column="dept_name" property="deptName"></result>
	</resultMap>

	<select id="getById" resultMap="department">
		SELECT id , dept_name FROM tbl_department WHERE id = #{id}
	</select>
</mapper>

測試代碼:

@Test
public void associationStepTest(){
    // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
    SqlSession sqlSession = null;
    try {
        sqlSession = sessionFactory.openSession();
        // 通過獲取接口代理對象來執行sql語句
        EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
        Employee employee = mapper.getByIdWithDeptStep(2);
        System.out.println(employee);
    } finally {
        // 資源關閉,放在finally中確保一定會執行
        sqlSession.close();
    }
}

測試結果:

DEBUG 05-08 23:15:31,272 ==>  Preparing: select id,last_name,email,gender, dept_id from tbl_employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:15:31,339 ==> Parameters: 2(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:15:31,370 ====>  Preparing: SELECT id , dept_name FROM tbl_department WHERE id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:15:31,376 ====> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:15:31,386 <====      Total: 1  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:15:31,387 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=Department{id=1, deptName='開發部', employeeList=null}}

四、collection定義關聯對象封裝結果集

(一)、普通查詢

DepartmentMapper.java 接口方法:

Department getByIdWithEmp(Integer id);

DepartmentMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.DepartmentMapper">

	<!-- collection 結果集的方式:定義關聯集合類型元素的封裝規則 -->
	<resultMap id="departmentWithEmp" type="com.wcg.mybatis.entity.Department">
		<id column="did" property="id"></id>
		<result column="dept_name" property="deptName"></result>
		<!--
			collection定義關聯集合類型的屬性的封裝規則
			ofType:指定集合裏面元素的類型
		-->
		<collection property="employeeList" ofType="com.wcg.mybatis.entity.Employee">
			<!-- 定義這個集合中元素的封裝規則 -->
			<id column="eid" property="id"></id>
			<result column="last_name" property="lastName"></result>
			<result column="gender" property="gender"></result>
			<result column="email" property="email"></result>
		</collection>
	</resultMap>
	<!-- collection 結果集的方式 -->
	<select id="getByIdWithEmp" resultMap="departmentWithEmp">
		SELECT
			d.id as did, d.dept_name,
			e.id as eid, e.last_name, e.email, e.gender
		FROM
			tbl_department d
		LEFT JOIN tbl_employee e ON e.dept_id = d.id
		WHERE d.id = #{id}
	</select>
</mapper>

測試代碼:

@Test
public void collectionTest(){
    // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
    SqlSession sqlSession = null;
    try {
        sqlSession = sessionFactory.openSession();
        // 通過獲取接口代理對象來執行sql語句
        DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
        Department department = mapper.getByIdWithEmp(1);
        System.out.println(department);
    } finally {
        // 資源關閉,放在finally中確保一定會執行
        sqlSession.close();
    }
}

測試結果:

DEBUG 05-08 23:40:25,183 ==>  Preparing: SELECT d.id as did, d.dept_name, e.id as eid, e.last_name, e.email, e.gender FROM tbl_department d LEFT JOIN tbl_employee e ON e.dept_id = d.id WHERE d.id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:40:25,291 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:40:25,333 <==      Total: 2  (BaseJdbcLogger.java:145) 
Department{id=1, deptName='開發部', employeeList=[Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=null}, Employee{id=7, lastName='FF', gender='0', email='[email protected]', department=null}]}

(二)、分步查詢

DepartmentMapper.java 接口方法:

​Employee getByIdWithDeptStep(Integer id);

​

DepartmentMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.DepartmentMapper">

	<resultMap id="departmentWithEmpStep" type="com.wcg.mybatis.entity.Department">
		<id column="id" property="id"></id>
		<result column="dept_name" property="deptName"></result>
		<collection property="employeeList"
					ofType="com.wcg.mybatis.entity.Employee"
					select="com.wcg.mybatis.dao.EmployeeMapperPlus.getEmpByDeptId"
					column="id">
		</collection>
	</resultMap>

	<!-- collection 結果集的方式 -->
	<select id="getByIdWithEmpStep" resultMap="departmentWithEmpStep">
		SELECT
			d.id, d.dept_name
		FROM
			tbl_department d
		WHERE d.id = #{id}
	</select>
</mapper>

EmployeeMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.EmployeeMapperPlus">
	<!--
		自定義某個javaBean的封裝規則
			type:自定義規則的Java類型
			id:唯一id方便引用
	  -->
	<resultMap id="employee" type="com.wcg.mybatis.entity.Employee">
		<!--
			指定主鍵列:
				id定義主鍵會底層有優化;
				column:字段
				property:JavaBean屬性
		-->
		<id column="id" property="id"></id>
		<!-- 定義普通列封裝規則 -->
		<result column="last_name" property="lastName"></result>
		<!-- 其他不指定的列會自動封裝:我們只要寫resultMap就把全部的映射規則都寫上。 -->
		<result column="gender" property="gender"></result>
		<result column="email" property="email"></result>
	</resultMap>
	<select id="getEmpByDeptId" resultMap="employee">
		select id,last_name,email,gender from tbl_employee where dept_id = #{id}
	</select>
</mapper>

測試代碼:

@Test
public void collectionStepTest(){
    // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
    SqlSession sqlSession = null;
    try {
        sqlSession = sessionFactory.openSession();
        // 通過獲取接口代理對象來執行sql語句
        DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
        Department department = mapper.getByIdWithEmpStep(1);
        System.out.println(department);
    } finally {
        // 資源關閉,放在finally中確保一定會執行
        sqlSession.close();
    }
}

測試結果:

DEBUG 05-08 23:43:04,330 ==>  Preparing: SELECT d.id, d.dept_name FROM tbl_department d WHERE d.id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,428 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,507 <==      Total: 1  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,509 ==>  Preparing: select id,last_name,email,gender from tbl_employee where dept_id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,509 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,511 <==      Total: 2  (BaseJdbcLogger.java:145) 
Department{id=1, deptName='開發部', employeeList=[Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=null}, Employee{id=7, lastName='FF', gender='0', email='[email protected]', department=null}]}

 

五、分步查詢延遲加載(懶加載)

(1)什麼是mybatis的懶加載

        通俗的講就是按需加載,我們需要什麼的時候再去進行什麼操作。而且先從單表查詢,需要時再從關聯表去關聯查詢,能大大提高數據庫性能,

  因爲查詢單表要比關聯查詢多張錶速度要快。

        在mybatis中,resultMap可以實現高級映射(使用association、collection實現一對一及一對多映射),association、collection具備延遲加載功能。

(二)、如何開啓懶加載

在mybatis中開啓延遲加載只要在全局配置文件中添加以下配置:

<settings>
    <!-- 打開延遲加載的開關 -->
    <setting name="lazyLoadingEnabled" value="true" />
    <!-- 將積極加載改爲消息加載即按需加載 -->
    <setting name="aggressiveLazyLoading" value="false" /> 
    <setting name="lazyLoadTriggerMethods" value=""/>
</settings>

mybatis全局配置:https://blog.csdn.net/qq_37776015/article/details/89892897

或者可以設置association或者collection中的fetchType屬性來覆蓋全局變量中的設置

  • lazy:懶加載
  • eager:急加載

 

根據上面的第四章:collection定義關聯對象封裝結果集的第二節:分步查詢的測試代碼如果沒有開啓懶加載的時候的測試結果爲:

DEBUG 05-08 23:43:04,330 ==>  Preparing: SELECT d.id, d.dept_name FROM tbl_department d WHERE d.id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,428 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,507 <==      Total: 1  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,509 ==>  Preparing: select id,last_name,email,gender from tbl_employee where dept_id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,509 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:43:04,511 <==      Total: 2  (BaseJdbcLogger.java:145) 
Department{id=1, deptName='開發部', employeeList=[Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=null}, Employee{id=7, lastName='FF', gender='0', email='[email protected]', department=null}]}

如果開啓了懶加載:

DEBUG 05-08 23:53:01,207 ==>  Preparing: SELECT d.id, d.dept_name FROM tbl_department d WHERE d.id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:53:01,278 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-08 23:53:01,362 <==      Total: 1  (BaseJdbcLogger.java:145) 
Department{id=1, deptName='開發部', employeeList=null}

我們會發現沒有開啓懶加載的時候執行了兩條sql語句,而開啓了懶加載的只執行了一條sql語句

把測試代碼進行修改:

@Test
public void collectionStepTest(){
    // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
    SqlSession sqlSession = null;
    try {
        sqlSession = sessionFactory.openSession();
        // 通過獲取接口代理對象來執行sql語句
        DepartmentMapper mapper = sqlSession.getMapper(DepartmentMapper.class);
        Department department = mapper.getByIdWithEmpStep(1);
        System.out.println(department);
        System.out.println(department.getEmployeeList());
    } finally {
        // 資源關閉,放在finally中確保一定會執行
        sqlSession.close();
    }
}

測試結果:

DEBUG 05-09 00:03:48,057 ==>  Preparing: SELECT d.id, d.dept_name FROM tbl_department d WHERE d.id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:03:48,164 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:03:48,222 <==      Total: 1  (BaseJdbcLogger.java:145) 
Department{id=1, deptName='開發部', employeeList=null}
DEBUG 05-09 00:03:48,225 ==>  Preparing: select id,last_name,email,gender from tbl_employee where dept_id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:03:48,226 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:03:48,227 <==      Total: 2  (BaseJdbcLogger.java:145) 
[Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=null}, Employee{id=7, lastName='FF', gender='0', email='[email protected]', department=null}]

通過查看測試結果可以發現,先從單表查詢,需要時再從關聯表去關聯查詢

 

注意:如果沒有在全局配置中設置lazyLoadTriggerMethods屬性的話,可能在調用toString方法時,使懶加載失效

 

六、鑑別器

概述:有時一個數據庫查詢語句會返回很多不同數據類型的結果集。鑑別器用於處理這種情況,還包括類的繼承層次結構,其表現相當於Java中的switch語句。

下面情況具體測試代碼:

EmployeeMapper.java 接口方法:

Employee getByIdWithDeptDiscriminator(Integer id);

EmployeeMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.EmployeeMapperPlus">
    <!-- =======================鑑別器============================ -->
	<!-- <discriminator javaType=""></discriminator>
		鑑別器:mybatis可以使用discriminator判斷某列的值,然後根據某列的值改變封裝行爲
		封裝Employee:
			如果查出的是女生:就把部門信息查詢出來,否則不查詢;
			如果是男生,把last_name這一列的值賦值給email;
	 -->
	<resultMap type="com.wcg.mybatis.entity.Employee" id="discriminatorEmployee">
		<id column="id" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
		<!--
            column:指定判定的列名
            javaType:列值對應的java類型  -->
		<discriminator javaType="string" column="gender">
			<!--女生  resultType:指定封裝的結果類型;不能缺少。/resultMap-->
			<case value="0" resultType="com.wcg.mybatis.entity.Employee">
				<association property="dept"
							 select="com.wcg.mybatis.dao.DepartmentMapper.getById"
							 column="dept_id">
				</association>
			</case>
			<!--男生 ;如果是男生,把last_name這一列的值賦值給email; -->
			<case value="1" resultType="com.wcg.mybatis.entity.Employee">
				<id column="id" property="id"/>
				<result column="last_name" property="lastName"/>
				<result column="last_name" property="email"/>
				<result column="gender" property="gender"/>
			</case>
		</discriminator>
	</resultMap>

	<select id="getByIdWithDeptDiscriminator" resultMap="discriminatorEmployee">
		select id,last_name,email,gender, dept_id from tbl_employee where id = #{id}
	</select>

</mapper>

DepartmentMapper.xml sql映射文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wcg.mybatis.dao.DepartmentMapper">

	<resultMap id="department" type="com.wcg.mybatis.entity.Department">
		<id column="did" property="id"></id>
		<result column="dept_name" property="deptName"></result>
	</resultMap>

	<select id="getById" resultMap="department">
		SELECT id , dept_name FROM tbl_department WHERE id = #{id}
	</select>
</mapper>

測試代碼1:

數據: 2    BB    0    [email protected]    1

@Test
public void discriminatorTest(){
    // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
    SqlSession sqlSession = null;
    try {
        sqlSession = sessionFactory.openSession();
        // 通過獲取接口代理對象來執行sql語句
        EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
        Employee employee = mapper.getByIdWithDeptDiscriminator(2);
        System.out.println(employee);
    } finally {
        // 資源關閉,放在finally中確保一定會執行
        sqlSession.close();
    }
}

測試結果1:

DEBUG 05-09 00:28:44,411 ==>  Preparing: select id,last_name,email,gender, dept_id from tbl_employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:28:44,499 ==> Parameters: 2(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:28:44,563 ====>  Preparing: SELECT id , dept_name FROM tbl_department WHERE id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:28:44,565 ====> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:28:44,568 <====      Total: 1  (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:28:44,568 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee{id=2, lastName='BB', gender='0', email='[email protected]', department=Department{id=1, deptName='開發部', employeeList=null}}

 得出結論:該gender爲0,走了分支一查詢出了部門信息

 

測試代碼2:

數據:3    CC    1    [email protected]    2

@Test
public void discriminatorTest(){
    // 獲取 SqlSession 的實例 。SqlSession 完全包含了面向數據庫執行 SQL 命令所需的所有方法。通過 SqlSession 實例來直接執行已映射的 SQL 語句
    SqlSession sqlSession = null;
    try {
        sqlSession = sessionFactory.openSession();
        // 通過獲取接口代理對象來執行sql語句
        EmployeeMapperPlus mapper = sqlSession.getMapper(EmployeeMapperPlus.class);
        Employee employee = mapper.getByIdWithDeptDiscriminator(3);
        System.out.println(employee);
    } finally {
        // 資源關閉,放在finally中確保一定會執行
        sqlSession.close();
    }
}

測試結果2:

DEBUG 05-09 00:32:43,805 ==>  Preparing: select id,last_name,email,gender, dept_id from tbl_employee where id = ?   (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:32:43,868 ==> Parameters: 3(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 05-09 00:32:43,890 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee{id=3, lastName='CC', gender='1', email='CC', department=null}

 得出結論:該gender爲1,走了分支二把last_name的值賦給了email

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章