三(二)、映射文件之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=joy52112225@iclound.com, gender=女], Employee [id=2, lastName=joy2x22222, email=joy52112225@iclound.com, gender=男], Employee [id=4, lastName=joy, email=joy521125@iclound.com, gender=女], Employee [id=5, lastName=joy, email=joy521125@iclound.com, gender=女], Employee [id=6, lastName=joy, email=joy521125@iclound.com, gender=女], Employee [id=7, lastName=joy, email=1602211057@qq.com, gender=女], Employee [id=8, lastName=joy, email=1602211058@qq.com, gender=女], Employee [id=25, lastName=joy1111, email=joy521125@icloud.com, gender=女], Employee [id=26, lastName=joy222, email=joy521125@icloud.com, 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=joy52112225@iclound.com}

 

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=joy52112225@iclound.com}, 2={lastName=[B@6e9a5ed8, gender=男, id=2, email=joy52112225@iclound.com}, 4={lastName=[B@7e057f43, gender=女, id=4, email=joy521125@iclound.com}, 5={lastName=[B@6c284af, gender=女, id=5, email=joy521125@iclound.com}, 6={lastName=[B@5890e879, gender=女, id=6, email=joy521125@iclound.com}, 7={lastName=[B@6440112d, gender=女, id=7, email=1602211057@qq.com}, 8={lastName=[B@31ea9581, gender=女, id=8, email=1602211058@qq.com}, 9={lastName=[B@231f98ef, id=9, email=zhumama@166.com}, 10={lastName=[B@7c137fd5, id=10, email=zhubaba@166.com}, 11={lastName=[B@183ec003, id=11, email=zhumama@166.com}, 12={lastName=[B@7d9d0818, id=12, email=zhubaba@166.com}, 13={lastName=[B@221a3fa4, id=13, email=zhumama@166.com}, 14={lastName=[B@451001e5, id=14, email=zhubaba@166.com}, 15={lastName=[B@2b40ff9c, gender=男, id=15, email=678@qq.com}, 16={lastName=[B@3e08ff24, gender=男, id=16, email=678@qq.com}, 17={lastName=[B@4d1c005e, gender=男, id=17, email=678@qq.com}, 18={lastName=[B@8462f31, gender=男, id=18, email=678@qq.com}, 19={lastName=[B@24569dba, gender=男, id=19, email=678@qq.com}, 20={lastName=[B@5ddeb7cb, gender=男, id=20, email=678@qq.com}, 21={lastName=[B@70ed52de, gender=男, id=21, email=678@qq.com}, 22={lastName=[B@496bc455, gender=男, id=22, email=678@qq.com}, 23={lastName=[B@59402b8f, gender=男, id=23, email=678@qq.com}, 25={lastName=[B@7188af83, gender=女, id=25, email=joy521125@icloud.com}, 26={lastName=[B@6be968ce, gender=女, id=26, email=joy521125@icloud.com}}

 二、resultMap:自定义某个javabean的封装规则

实体类Employee.java添加的部门字段:
三(二)、映射文件之select返回和resultMap
 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

添加了部门的实体类:

三(二)、映射文件之select返回和resultMap
 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=joy52112225@iclound.com, 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=joy52112225@iclound.com, 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=joy52112225@iclound.com, 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

三(二)、映射文件之select返回和resultMap
 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=joy52112225@iclound.com, gender=女, dept=Department [id=1, departmentName=开发部]]

5.分步查询的懒加载说明

接着上面的运行结果,查看控制台查询了两条SQL:

三(二)、映射文件之select返回和resultMap

此时,如果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

查看控制台日志:

三(二)、映射文件之select返回和resultMap

 

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=joy52112225@iclound.com, gender=女, dept=null], Employee [id=5, lastName=joy, email=joy521125@iclound.com, 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, lastName=joy52112225@iclound.com, email=joy2x22222, gender=男, dept=null]

如果把数据中该条记录性别改为“女”:

测试 bean中的列表查询:

测试 bean中的列表查询:Employee [id=2, lastName=joy2x22222, email=joy52112225@iclound.com, gender=女, dept=Department [id=2, departmentName=测试部]]

 

上一篇:三(一)、mybatis映射文件-增删改和参数处理


下一篇:ES中的version机制