1. 程式人生 > 其它 >三(二)、對映檔案之select返回和resultMap

三(二)、對映檔案之select返回和resultMap

目錄結構同三(一)、mybatis對映檔案-增刪改和引數處理中的目錄結構

這裡需要再新增一張表:

CREATE TABLE `tbl_department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `depart_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

一、select 返回

1.select 返回物件:

三(一)、mybatis對映檔案-增刪改和引數處理中的單個參數和多個引數中的查詢一樣;這裡不再多說了;

2.select 返回list

介面EmployeeMapper.java:

List<Employee> getEmps(String param);

對映檔案EmployeeMapper.xml;

  • parameterType 可以不傳
  • resultType 如果返回的是一個集合,要寫集合中元素的型別
<select id="getEmps"  resultType="entity.Employee">
        select ID AS id,LAST_NAME AS
        lastName,gender as gender,email as email from
        tbl_employee where LAST_NAME like #{e}
    
</select>

junit 測試類:

 1 @Test
 2     public void test06() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(inputStream); 8 // 獲取openSession 不會自動提交資料 9 openSession = sqlSessionFactory.openSession(true); 10 EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class); 11 12 List<Employee> employees = mapper.getEmps("%joy%"); 13 System.out.println("測試 select 返回list:" + employees); 14 15 } catch (Exception e) { 16 // TODO: handle exception 17 } finally { 18 if (openSession != null) { 19 openSession.close(); 20 } 21 22 } 23 }

執行結果:

測試 select 返回list:[Employee [id=1, lastName=joy33333, [email protected], gender=女], Employee [id=2, lastName=joy2x22222, [email protected], gender=男], Employee [id=4, lastName=joy, [email protected], gender=女], Employee [id=5, lastName=joy, [email protected], gender=女], Employee [id=6, lastName=joy, [email protected], gender=女], Employee [id=7, lastName=joy, [email protected], gender=女], Employee [id=8, lastName=joy, [email protected], gender=女], Employee [id=25, lastName=joy1111, [email protected], gender=女], Employee [id=26, lastName=joy222, [email protected], gender=女]]

3.select 返回單條資料的map

介面EmployeeMapper.java:

  • 返回一條記錄的map,key就是列名,值就是對於的值
Employee getEmpByMap(Map<String, Object> map);

對映檔案EmployeeMapper.xml;

<select id="getMapById"  resultType="map">
        select ID AS id,LAST_NAME AS
        lastName,gender as gender,email as email from
        tbl_employee where id = #{id}
    </select>

junit 測試類:

 1 @Test
 2     public void test06() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
11             Map<String, Object> map = mapper.getMapById(1);
12             System.out.println("測試 select 返回單條資料的map:" + map);
13 
14         } catch (Exception e) {
15             // TODO: handle exception
16         } finally {
17             if (openSession != null) {
18                 openSession.close();
19             }
20 
21         }
22     }

執行結果:

測試 select 返回單條資料的map:{lastName=[B@202b0582, gender=女, id=1, [email protected]}

4.select 返回多條資料的map

介面EmployeeMapper.java:

  • 多條記錄封裝一個map。Map<Integer, Employee> :鍵是id,value 是資料物件
  • @MapKey 告訴mybatis 封裝map的時候使用哪個屬性作為主鍵
@MapKey("id")
    Map<Integer, Employee> getMaps();

對映檔案EmployeeMapper.xml:

 <select id="getMaps"  resultType="map">
        select ID AS id,LAST_NAME AS
        lastName,gender as gender,email as email from
        tbl_employee 
    </select>

junit 測試類:

 1 @Test
 2     public void test06() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
11 
12             Map<Integer, Employee> maps = mapper.getMaps();
13             System.out.println("測試 select 返回多條資料的map:" + maps);
14 
15         } catch (Exception e) {
16             // TODO: handle exception
17         } finally {
18             if (openSession != null) {
19                 openSession.close();
20             }
21 
22         }
23     }

執行結果:

測試 select 返回多條資料的map:{1={lastName=[B@268f106e, gender=女, id=1, [email protected]}, 2={lastName=[B@6e9a5ed8, gender=男, id=2, [email protected]}, 4={lastName=[B@7e057f43, gender=女, id=4, [email protected]}, 5={lastName=[B@6c284af, gender=女, id=5, [email protected]}, 6={lastName=[B@5890e879, gender=女, id=6, [email protected]}, 7={lastName=[B@6440112d, gender=女, id=7, [email protected]}, 8={lastName=[B@31ea9581, gender=女, id=8, [email protected]}, 9={lastName=[B@231f98ef, id=9, [email protected]}, 10={lastName=[B@7c137fd5, id=10, [email protected]}, 11={lastName=[B@183ec003, id=11, [email protected]}, 12={lastName=[B@7d9d0818, id=12, [email protected]}, 13={lastName=[B@221a3fa4, id=13, [email protected]}, 14={lastName=[B@451001e5, id=14, [email protected]}, 15={lastName=[B@2b40ff9c, gender=男, id=15, [email protected]}, 16={lastName=[B@3e08ff24, gender=男, id=16, [email protected]}, 17={lastName=[B@4d1c005e, gender=男, id=17, [email protected]}, 18={lastName=[B@8462f31, gender=男, id=18, [email protected]}, 19={lastName=[B@24569dba, gender=男, id=19, [email protected]}, 20={lastName=[B@5ddeb7cb, gender=男, id=20, [email protected]}, 21={lastName=[B@70ed52de, gender=男, id=21, [email protected]}, 22={lastName=[B@496bc455, gender=男, id=22, [email protected]}, 23={lastName=[B@59402b8f, gender=男, id=23, [email protected]}, 25={lastName=[B@7188af83, gender=女, id=25, [email protected]}, 26={lastName=[B@6be968ce, gender=女, id=26, [email protected]}}

二、resultMap:自定義某個javabean的封裝規則

實體類Employee.java新增的部門欄位:
 1 package introduction;
 2 
 3 public class Employee {
 4 
 5     private Integer id;
 6     private String lastName;
 7     private String email;
 8     private String gender;
 9     private Department dept;
10 
11     public Integer getId() {
12         return id;
13     }
14 
15     public void setId(Integer id) {
16         this.id = id;
17     }
18 
19     public String getLastName() {
20         return lastName;
21     }
22 
23     public void setLastName(String lastName) {
24         this.lastName = lastName;
25     }
26 
27     public String getEmail() {
28         return email;
29     }
30 
31     public void setEmail(String email) {
32         this.email = email;
33     }
34 
35     public String getGender() {
36         return gender;
37     }
38 
39     public void setGender(String gender) {
40         this.gender = gender;
41     }
42 
43     public Department getDept() {
44         return dept;
45     }
46 
47     public void setDept(Department dept) {
48         this.dept = dept;
49     }
50 
51     @Override
52     public String toString() {
53         return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", dept="
54                 + dept + "]";
55     }
56 
57 }
View Code

添加了部門的實體類:

 1 package introduction;
 2 
 3 import java.util.List;
 4 
 5 public class Department {
 6 
 7     private Integer id;
 8     private String departmentName;
 9     private List<Employee> empList;
10 
11     public Integer getId() {
12         return id;
13     }
14 
15     public void setId(Integer id) {
16         this.id = id;
17     }
18 
19     public String getDepartmentName() {
20         return departmentName;
21     }
22 
23     public void setDepartmentName(String departmentName) {
24         this.departmentName = departmentName;
25     }
26 
27     public List<Employee> getEmpList() {
28         return empList;
29     }
30 
31     public void setEmpList(List<Employee> empList) {
32         this.empList = empList;
33     }
34 
35     @Override
36     public String toString() {
37         return "Department [id=" + id + ", departmentName=" + departmentName + "]";
38     }
39 
40 }
View Code

1.自定義java bean 封裝規則的例項:

介面檔案EmployeeMapper.java:

Employee testResultType(Integer id);

對映檔案EmployeeMapper.xml:

 1 <!-- 自定義某個javabean的封裝規則, type:自定義的java型別 id:唯一ID,方便引用 -->
 2     <resultMap type="introduction.Employee" id="MyEmp">
 3         <!-- 指定主鍵列的封裝規則 id 定義主鍵,底層有優化 column:指定哪一列 property:指定對應的javabean屬性 -->
 4         <id column="id" property="id" />
 5         <!-- 指定指定列封裝規則 不指定列會自動封裝 推薦 把全部的對映規則都寫上 -->
 6         <result column="last_name" property="lastName" />
 7         <result column="email" property="email" />
 8         <result column="gender" property="gender" />
 9     </resultMap>
10 
11     <select id="testResultType" resultMap="MyEmp">
12         select
13         t01.* from
14         tbl_employee t01 where id=#{id}
15     </select>

Junit測試類:

 1 @Test
 2     public void test01() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
11 
12             Employee testResultType = mapper.testResultType(1);
13             System.out.println("測試 stestResultType:" + testResultType);
14         } catch (Exception e) {
15             // TODO: handle exception
16         } finally {
17             if (openSession != null) {
18                 openSession.close();
19             }
20 
21         }
22     }

執行結果:

測試 stestResultType:Employee [id=1, lastName=joy33333, [email protected], gender=女, dept=null]

2.關聯查詢級聯屬性封裝:

介面檔案EmployeeMapper.java:

1 package dao;
2 
3 import introduction.Employee;
4 
5 public interface EmployeeMapper {
6 
7     Employee testResultType(Integer id);
8 
9 }

對映檔案EmployeeMapper.xml

  • type:自定義的java型別 id:唯一ID,方便引用
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="dao.EmployeeMapper">
 6 
 7 
 8     <!-- 自定義某個javabean的封裝規則, type:自定義的java型別 id:唯一ID,方便引用 -->
 9     <resultMap type="introduction.Employee" id="MyEmp">
10         <!-- 指定主鍵列的封裝規則 id 定義主鍵,底層有優化 column:指定哪一列 property:指定對應的javabean屬性 -->
11         <id column="id" property="id" />
12         <!-- 指定指定列封裝規則 不指定列會自動封裝 推薦 把全部的對映規則都寫上 -->
13         <result column="last_name" property="lastName" />
14         <result column="email" property="email" />
15         <result column="gender" property="gender" />
16         <result column="d_id" property="dept.id" />
17         <result column="depart_name" property="dept.departmentName" />
18     </resultMap>
19 
20     <select id="testResultType" resultMap="MyEmp">
21         select
22         t01.*,t02.depart_name from
23         tbl_employee t01 left join tbl_department
24         t02 on t01.d_id = t02.id where t01.id =#{id}
25     </select>
26 </mapper>

junit測試類:

 1 @Test
 2     public void test01() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
11 
12             Employee testResultType = mapper.testResultType(1);
13             System.out.println("測試 stestResultType:" + testResultType);
14         } catch (Exception e) {
15             // TODO: handle exception
16         } finally {
17             if (openSession != null) {
18                 openSession.close();
19             }
20 
21         }
22     }

執行測試結果:

測試 stestResultType:Employee [id=1, lastName=joy33333, [email protected], gender=女, dept=Department [id=1, departmentName=開發部]]

3.關聯查詢association級聯屬性封裝:

介面檔案EmployeeMapper.java:

Employee testResultType2(Integer id);

對映檔案EmployeeMapper.xml

  • type:自定義的java型別 id:唯一ID,方便引用
 1 <!-- 自定義某個javabean的封裝規則, type:自定義的java型別 id:唯一ID,方便引用 -->
 2     <resultMap type="introduction.Employee" id="MyEmp2">
 3         <!-- 指定主鍵列的封裝規則 id 定義主鍵,底層有優化 column:指定哪一列 property:指定對應的javabean屬性 -->
 4         <id column="id" property="id" />
 5         <!-- 指定指定列封裝規則 不指定列會自動封裝 推薦 把全部的對映規則都寫上 -->
 6         <result column="last_name" property="lastName" />
 7         <result column="email" property="email" />
 8         <result column="gender" property="gender" />
 9         <!-- association可以指定聯合的javaBean物件
10         property=”dept“ 指定哪個屬性是聯合的物件
11         javaType:指定這個屬性物件的型別;【不能省略】
12          -->
13         <association property="dept"
14             javaType="introduction.Department">
15             <result column="d_id" property="id" />
16             <result column="depart_name" property="departmentName" />
17         </association>
18     </resultMap>
19 
20     <select id="testResultType2" resultMap="MyEmp2">
21         select
22         t01.*,t02.depart_name from
23         tbl_employee t01 left join tbl_department
24         t02 on t01.d_id = t02.id where t01.id =#{id}
25     </select>

junit測試類:

 1 @Test
 2     public void test02() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
11 
12             Employee testResultType = mapper.testResultType2(1);
13             System.out.println("測試 stestResultType:" + testResultType);
14         } catch (Exception e) {
15             // TODO: handle exception
16         } finally {
17             if (openSession != null) {
18                 openSession.close();
19             }
20 
21         }
22     }

執行結果:

測試 stestResultType:Employee [id=1, lastName=joy33333, [email protected], gender=女, dept=Department [id=1, departmentName=開發部]]

4.關聯查詢association 分步查尋:

介面檔案

EmployeeMapper.java:

Employee getEmpByIdStep(Integer id);

DepartmentMapper.java:

    Department getDepartmentById(Integer id);

對映檔案EmployeeMapper.xml

  • type:自定義的java型別 id:唯一ID,方便引用
 1 <!-- 自定義某個javabean的封裝規則, type:自定義的java型別 id:唯一ID,方便引用 -->
 2     <resultMap type="introduction.Employee" id="MyEmp3">
 3         <!-- 指定主鍵列的封裝規則 id 定義主鍵,底層有優化 column:指定哪一列 property:指定對應的javabean屬性 -->
 4         <id column="id" property="id" />
 5         <!-- 指定指定列封裝規則 不指定列會自動封裝 推薦 把全部的對映規則都寫上 -->
 6         <result column="last_name" property="lastName" />
 7         <result column="email" property="email" />
 8         <result column="gender" property="gender" />
 9         
10         <!-- association 定義關聯物件的封裝規則
11         select: 表明當前屬性時呼叫select 指定的方法查出的結果
12         column:指定哪一列的值傳給方法
13         流程:使用select 指定的方法(傳入column指定的這列引數的值)查出物件,並封裝property物件
14          -->
15         <association property="dept" select="dao.DepartmentMapper.getDepartmentById" column="d_id">
16         </association>
17     </resultMap>
18     
19     <select id="getEmpByIdStep" resultMap="MyEmp3">
20         SELECT * FROM tbl_employee WHERE ID= #{id}
21     </select>

DepartmentMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="dao.DepartmentMapper">
 6 
 7     <select id="getDepartmentById" resultType="introduction.Department">
 8         SELECT id,depart_name as departmentName  FROM TBL_DEPARTMENT WHERE ID= #{id}
 9     </select>
10 
11 </mapper>
View Code

junit測試類:

 1 @Test
 2     public void test03() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
11 
12             Employee testResultType = mapper.getEmpByIdStep(1);
13             System.out.println("測試 分步:" + testResultType);
14         } catch (Exception e) {
15             // TODO: handle exception
16         } finally {
17             if (openSession != null) {
18                 openSession.close();
19             }
20 
21         }
22     }

執行結構:

測試 分步:Employee [id=1, lastName=joy33333, [email protected], gender=女, dept=Department [id=1, departmentName=開發部]]

5.分步查詢的懶載入說明

接著上面的執行結果,檢視控制檯查詢了兩條SQL:

此時,如果Junit測試只查詢單條一條SQL中的資料,那麼該分步查詢只執行一條SQL

 1 @Test
 2     public void test04() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
11 
12             Employee testResultType = mapper.getEmpByIdStep(1);
13             System.out.println("測試 分步 只查一條SQL:" + testResultType.getLastName());
14         } catch (Exception e) {
15             // TODO: handle exception
16         } finally {
17             if (openSession != null) {
18                 openSession.close();
19             }
20 
21         }
22     }

執行結果為:

測試 分步 只查一條SQL:joy33333

檢視控制檯日誌:

6.關聯查詢 collection定義關聯封裝規則:

需求:查詢部門下所有的員工;所有員工放入 list中;即 部門物件中 把部門資訊放入對應的欄位,把該部門下的員工放入list中;

介面檔案EmployeeMapper.java:

    Department getDepartmentByIdPlus(Integer id);

對映檔案EmployeeMapper.xml

  • type:自定義的java型別 id:唯一ID,方便引用
 1 <!-- collection 巢狀結果集的方式:定義關聯的集合型別元素的封裝規則 -->
 2 
 3     <resultMap type="introduction.Department" id="MyDept">
 4         <id column="id" property="id" />
 5         <result column="depart_name" property="departmentName" />
 6         <!-- collection 定義關聯集合型別的屬性的封裝規則 ofType:指定集合裡面元素的型別 -->
 7         <collection property="empList"
 8             ofType="introduction.Employee">
 9             <id column="eid" property="id" />
10             <result column="last_name" property="lastName" />
11             <result column="gender" property="gender" />
12             <result column="email" property="email" />
13         </collection>
14 
15     </resultMap>
16     <select id="getDepartmentByIdPlus" resultMap="MyDept">
17         SELECT
18         T01.id,
19         T01.depart_name,
20         T02.id eid,
21         T02.last_name,
22         T02.gender,
23         T02.email
24         FROM
25         TBL_DEPARTMENT t01
26         LEFT JOIN tbl_employee T02 ON T01.ID = T02.D_ID
27         WHERE
28         T01.ID = #{id}
29     </select>

junit測試類:

 1 @Test
 2     public void test05() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
11 
12             Department testResultType = mapper.getDepartmentByIdPlus(1);
13             System.out.println("測試 bean中的列表查詢:" + testResultType);// 顯示 一個部門資訊
14             System.out.println("測試 bean中的列表查詢:" + testResultType.getEmpList());// 部門下的所有員工
15         } catch (Exception e) {
16             // TODO: handle exception
17         } finally {
18             if (openSession != null) {
19                 openSession.close();
20             }
21 
22         }
23     }

執行結果:

測試 bean中的列表查詢:Department [id=1, departmentName=開發部]

測試 bean中的列表查詢:[Employee [id=1, lastName=joy33333, [email protected], gender=女, dept=null], Employee [id=5, lastName=joy, [email protected], gender=女, dept=null]]

7.關聯查詢 collection 分步查詢:

同理可以實現懶載入,這裡不贅述了;

介面檔案EmployeeMapper.java:

Department getDepartmentByIdStep(Integer id);

對映檔案EmployeeMapper.xml

  • type:自定義的java型別 id:唯一ID,方便引用
 1 <!-- 分步查詢(可以實現懶載入) collection 巢狀結果集的方式:定義關聯的集合型別元素的封裝規則 -->
 2 
 3     <resultMap type="introduction.Department" id="MyDept2">
 4         <id column="id" property="id" />
 5         <result column="depart_name" property="departmentName" />
 6         <!-- collection 定義關聯集合型別的屬性的封裝規則 ofType:指定集合裡面元素的型別 -->
 7         <collection property="empList"
 8             ofType="introduction.Employee"
 9             select="dao.EmployeeMapper.getListByDid" column="{id=id}">
10         </collection>
11 
12     </resultMap>
13     <select id="getDepartmentByIdStep" resultMap="MyDept2">
14         SELECT
15         T01.id,
16         T01.depart_name
17 
18         FROM
19         TBL_DEPARTMENT t01
20         WHERE
21         T01.ID = #{id}
22     </select>

junit測試類:

 1 @Test
 2     public void test06() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             DepartmentMapper mapper = openSession.getMapper(DepartmentMapper.class);
11 
12             Department testResultType = mapper.getDepartmentByIdStep(1);
13             System.out.println("測試 bean中的列表查詢:" + testResultType.getDepartmentName());// 顯示 一個部門資訊
14         } catch (Exception e) {
15             // TODO: handle exception
16         } finally {
17             if (openSession != null) {
18                 openSession.close();
19             }
20 
21         }
22     }

執行結果:

測試 bean中的列表查詢:開發部;

擴充套件內容:

多列值的傳遞; 將多列的值封裝map傳遞 column={key1=column1,key2=column}; key為 目標xml中的佔位符的名稱;即

SELECT * FROM tbl_employee WHERE D_ID= #{id};id 其他屬性: fetchType="lazy":表示延遲載入;

按需載入 eager:表示立即 <collection property="empList" ofType="introduction.Employee"

select="dao.EmployeeMapper.getListByDid" column="{did=id}">

8.鑑別器:

說明:mybatis可以使用discriminator 判斷某列的值,然後根據某列的值改變封裝行為;

介面檔案EmployeeMapper.java:

    Employee getEmpByIdStepDis(Integer id);

對映檔案EmployeeMapper.xml

  • type:自定義的java型別 id:唯一ID,方便引用
 1 <resultMap type="introduction.Employee" id="MyEmpDis">
 2         <id column="id" property="id" />
 3         <result column="last_name" property="lastName" />
 4         <result column="email" property="email" />
 5         <result column="gender" property="gender" />
 6         <discriminator javaType="string" column="gender">
 7             <case value="女" resultType="introduction.Employee">
 8                     <association property="dept" select="dao.DepartmentMapper.getDepartmentById" column="d_id">
 9                 </association>
10             </case>
11             <case value="男" resultType="introduction.Employee">
12                     <id column="id" property="id"/>
13                     <result column="last_name" property="email" />
14                     <result column="email" property="lastName" />
15                     <result column="gender" property="gender" />
16             </case>
17         </discriminator>
24     </resultMap>
25     
26     <select id="getEmpByIdStepDis" resultMap="MyEmpDis">
27         SELECT * FROM tbl_employee WHERE ID= #{id}
28     </select>
29 </mapper>

DepartmentMapper.xml:

1 <select id="getDepartmentById"
2         resultType="introduction.Department">
3         SELECT id,depart_name as departmentName FROM TBL_DEPARTMENT WHERE ID= #{id}
4     </select>

junit測試類:

 1 @Test
 2     public void test07() {
 3         String resource = "mybatis-config.xml";
 4         SqlSession openSession = null;
 5         try {
 6             InputStream inputStream = Resources.getResourceAsStream(resource);
 7             SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
 8             // 獲取openSession 不會自動提交資料
 9             openSession = sqlSessionFactory.openSession(true);
10             EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
11 
12             Employee testResultType = mapper.getEmpByIdStepDis(2);
13             System.out.println("測試 bean中的列表查詢:" + testResultType);
14         } catch (Exception e) {
15             // TODO: handle exception
16         } finally {
17             if (openSession != null) {
18                 openSession.close();
19             }
20 
21         }
22     }

執行結果:

測試 bean中的列表查詢:

測試 bean中的列表查詢:Employee [id=2, [email protected], email=joy2x22222, gender=男, dept=null]

如果把資料中該條記錄性別改為“女”:

測試 bean中的列表查詢:

測試 bean中的列表查詢:Employee [id=2, lastName=joy2x22222, [email protected], gender=女, dept=Department [id=2, departmentName=測試部]]

我從來不相信什麼懶洋洋的自由。我向往的自由是通過勤奮和努力實現的更廣闊的人生。 我要做一個自由又自律的人,靠勢必實現的決心認真地活著。