一、resultMap自定义结果集映射规则

示例如下:

接口定义:
package com.mybatis.dao; import com.mybatis.bean.Employee; public interface EmployeeMapper {
public Employee getEmpById(Integer id);
} mapper定义:
<?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.mybatis.dao.EmployeeMapper">
<!--
自定义某个javaBean的封装规则
type:自定义规则的Java类型
id:唯一标示id,方便引用
-->
<resultMap id="EmpMap" type="com.mybatis.bean.Employee">
<!--
指定主键列的封装规则
id定义主键会底层有优化;
column:指定哪一列
property:指定对应的javaBean属性
-->
<id column="id" property="id"/>
<!-- 定义普通列封装规则 -->
<result column="last_name" property="lastName"/>
<!-- 其他不指定的列会自动封装:但是最好只要写resultMap就把全部的映射规则都写上。 -->
<result column="email" property="email"/>
<result column="gender" property="gender"/>
</resultMap>
<!--public Employee getEmpById(Integer id);-->
<!-- resultMap:自定义结果集映射规则; -->
<select id="getEmpById" resultMap="EmpMap">
select * from tbl_employee where id=#{id}
</select>
</mapper> 测试代码:
package com.mybatis.demo; import java.io.*;
import java.util.*; import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;
import org.junit.Test; public class MyTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testResultMap() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpById(1);
System.out.println(employee);
} finally {
openSession.close();
}
}
}

二、resultMap使用场景

(一)、查询Employee的同时查询员工对应的部门。

1、联合查询:级联属性封装结果集。

员工实体类Employee

package com.mybatis.bean;

public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private Department dept; public Employee() {
} public Employee(String lastName, String email, Integer gender) {
this.lastName = lastName;
this.email = email;
this.gender = gender;
} public Employee(Integer id, String lastName, String email, Integer gender) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Integer getGender() {
return gender;
} public void setGender(Integer gender) {
this.gender = gender;
} public Department getDept() {
return dept;
} public void setDept(Department dept) {
this.dept = dept;
} @Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
", dept=" + dept +
'}';
}
}

部门实体类Deptment

package com.mybatis.bean;

public class Department {
private Integer id;
private String departmentName; public Department() {
} public Department(Integer id, String departmentName) {
this.id = id;
this.departmentName = departmentName;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getDepartmentName() {
return departmentName;
} public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
} @Override
public String toString() {
return "Department{" +
"id=" + id +
", departmentName='" + departmentName + '\'' +
'}';
}
}

建立部门表及修改员工表的sql脚本如下:

CREATE TABLE tbl_dept(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
dept_name VARCHAR(255)
); alter table tbl_employee add column d_id int(11); alter table tbl_employee add constraint fk_emp_dept
foreign key(d_id) references tbl_dept(id);

示例如下:

接口定义:
package com.mybatis.dao; import com.mybatis.bean.Employee; public interface EmployeeMapper {
public Employee getEmpByIdWithDept(Integer id);
} mapper定义:
<?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.mybatis.dao.EmployeeMapper">
<!--联合查询:级联属性封装结果集-->
<resultMap id="EmpMap" type="com.mybatis.bean.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="did" property="dept.id"/>
<result column="dept_name" property="dept.departmentName"/>
</resultMap>
<!--public Employee getEmpById(Integer id);-->
<select id="getEmpByIdWithDept" resultMap="EmpMap">
SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
WHERE e.d_id=d.id AND e.id=#{id}
</select>
</mapper> 测试代码:
package com.mybatis.demo; import java.io.*;
import java.util.*; import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;
import org.junit.Test; public class MyTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testResultMap() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpByIdWithDept(1);
System.out.println(employee);
} finally {
openSession.close();
}
}
}

2、联合查询:使用association定义关联的单个对象的封装规则

示例如下:

接口定义:
package com.mybatis.dao; import com.mybatis.bean.Employee; public interface EmployeeMapper {
public Employee getEmpByIdWithDept(Integer id);
} mapper定义:
<?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.mybatis.dao.EmployeeMapper">
<!--使用association定义关联的单个对象的封装规则-->
<resultMap id="EmpMap" type="com.mybatis.bean.Employee">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<!--
association可以指定联合的javaBean对象
property="dept":指定哪个属性是联合的对象
javaType:指定这个属性对象的类型[不能省略]
-->
<association property="dept" javaType="com.mybatis.bean.Department">
<id column="did" property="id"/>
<result column="dept_name" property="departmentName"/>
</association>
</resultMap>
<!--public Employee getEmpById(Integer id);-->
<select id="getEmpByIdWithDept" resultMap="EmpMap">
SELECT e.id id,e.last_name last_name,e.gender gender,e.d_id d_id,
d.id did,d.dept_name dept_name FROM tbl_employee e,tbl_dept d
WHERE e.d_id=d.id AND e.id=#{id}
</select>
</mapper> 测试代码:
package com.mybatis.demo; import java.io.*;
import java.util.*; import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;
import org.junit.Test; public class MyTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testResultMap() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpByIdWithDept(1);
System.out.println(employee);
} finally {
openSession.close();
}
}
}

3、使用association进行分步查询

DeptmentMapper接口定义:
package com.mybatis.dao; import com.mybatis.bean.Department; public interface DeptmentMapper {
public Department getDeptById(Integer id);
} DeptmentMapper.xml定义
<?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.mybatis.dao.DeptmentMapper">
<!--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>
</mapper> EmployeeMapper接口定义:
package com.mybatis.dao; import com.mybatis.bean.Employee; public interface EmployeeMapper {
public Employee getEmpByIdWithDept(Integer id);
} EmployeeMapper.xml定义:
<?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.mybatis.dao.EmployeeMapper">
<!--
使用association进行分步查询:
1、先按照员工id查询员工信息
2、根据查询员工信息中的d_id值去部门表查出部门信息
3、部门设置到员工中;
-->
<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.DeptmentMapper.getDeptById"
column="d_id">
</association>
</resultMap> <select id="getEmpByIdWithDept" resultMap="MyEmpByStep">
select * from tbl_employee where id=#{id}
</select>
</mapper> 测试代码:
package com.mybatis.demo; import java.io.*;
import java.util.*; import com.mybatis.bean.Department;
import com.mybatis.bean.Employee;
import com.mybatis.dao.DeptmentMapper;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;
import org.junit.Test; public class MyTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testResultMap() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession(true);
try {
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Employee employee = mapper.getEmpByIdWithDept(1);
System.out.println(employee);
System.out.println(employee.getDept());
} finally {
openSession.close();
}
}
}

4、延迟加载(懒加载、按需加载)

Employee==>Dept:
每次查询Employee对象的时候,部门信息在使用的时候再去查询;
只需在分步查询的基础之上加上两个配置:

<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>

(二)、查询部门的同时查询出该部门的所有员工。

1、嵌套结果集的方式,使用collection标签定义关联的集合类型的属性

Department实体类修改如下:

package com.mybatis.bean;

import java.util.List;

public class Department {
private Integer id;
private String departmentName;
private List<Employee> emps; public Department() {
} public Department(Integer id, String departmentName) {
this.id = id;
this.departmentName = departmentName;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getDepartmentName() {
return departmentName;
} public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
} public List<Employee> getEmps() {
return emps;
} public void setEmps(List<Employee> emps) {
this.emps = emps;
} @Override
public String toString() {
return "Department{" +
"id=" + id +
", departmentName='" + departmentName + '\'' +
", emps=" + emps +
'}';
}
}

示例如下:

接口定义:
package com.mybatis.dao; import com.mybatis.bean.Department; public interface DeptmentMapper {
public Department getDeptByIdWithEmp(Integer id);
} mapper定义:
<?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.mybatis.dao.DeptmentMapper">
<!--嵌套结果集的方式,使用collection标签定义关联的集合类型的属性封装规则 -->
<resultMap id="MyDept" type="com.mybatis.bean.Department">
<id column="did" property="id"/>
<result column="dept_name" property="departmentName"/>
<!--
collection定义关联集合类型的属性的封装规则
ofType:指定集合里面元素的类型
-->
<collection property="emps" ofType="com.mybatis.bean.Employee">
<id column="eid" property="id"/>
<result column="last_name" property="lastName"/>
<result column="email" property="email"/>
<result column="gender" property="gender"/>
</collection>
</resultMap>
<select id="getDeptByIdWithEmp" resultMap="MyDept">
SELECT d.id did,d.dept_name dept_name,
e.id eid,e.last_name last_name,e.email email,e.gender gender
FROM tbl_dept d
LEFT JOIN tbl_employee e
ON d.id=e.d_id
WHERE d.id=#{id}
</select>
</mapper> 测试代码:
package com.mybatis.demo; import java.io.*;
import java.util.*; import com.mybatis.bean.Department;
import com.mybatis.bean.Employee;
import com.mybatis.dao.DeptmentMapper;
import com.mybatis.dao.EmployeeMapper;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;
import org.junit.Test; public class MyTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testResultMap() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession(true);
try {
DeptmentMapper mapper=openSession.getMapper(DeptmentMapper.class);
Department department=mapper.getDeptByIdWithEmp(1);
System.out.println(department);
} finally {
openSession.close();
}
}
}

2、分步查询

示例代码:

EmployeeMapper接口定义:
package com.mybatis.dao; import com.mybatis.bean.Employee; import java.util.List; public interface EmployeeMapper {
public List<Employee> getEmpsByDeptId(Integer deptId);
} EmployeeMapper.xml文件定义:
<?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.mybatis.dao.EmployeeMapper">
<select id="getEmpsByDeptId" resultType="com.mybatis.bean.Employee">
select * from tbl_employee where d_id=#{deptId}
</select>
</mapper> DeptmentMapper接口定义:
package com.mybatis.dao; import com.mybatis.bean.Department; public interface DeptmentMapper {
public Department getDeptByIdWithEmpStep(Integer id);
} DeptmentMapper.xml文件定义:
<?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.mybatis.dao.DeptmentMapper">
<resultMap id="MyDeptStep" type="com.mybatis.bean.Department">
<id column="id" property="id"/>
<id column="dept_name" property="departmentName"/>
<collection property="emps"
select="com.mybatis.dao.EmployeeMapper.getEmpsByDeptId"
column="id"/>
</resultMap> <select id="getDeptByIdWithEmpStep" resultMap="MyDeptStep">
select id,dept_name departmentName from tbl_dept where id=#{id}
</select>
</mapper> 测试代码:
package com.mybatis.demo; import com.mybatis.bean.Department;
import com.mybatis.dao.DeptmentMapper;
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.Test; import java.io.IOException;
import java.io.InputStream; public class MyTest {
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
} @Test
public void testResultMap() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession(true);
try {
DeptmentMapper mapper = openSession.getMapper(DeptmentMapper.class);
Department department = mapper.getDeptByIdWithEmpStep(2);
System.out.println(department);
} finally {
openSession.close();
}
}
}

扩展:多列的值传递过去:

  将多列的值封装map传递;
  column="{key1=column1,key2=column2}"
  fetchType="lazy":表示使用延迟加载;
    - lazy:延迟加载
    - eager:立即加载

<?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.mybatis.dao.DeptmentMapper">
<resultMap id="MyDeptStep" type="com.mybatis.bean.Department">
<id column="id" property="id"/>
<id column="dept_name" property="departmentName"/>
<!-- 扩展:多列的值传递过去:
将多列的值封装map传递;
column="{key1=column1,key2=column2}"
fetchType="lazy":表示使用延迟加载;
- lazy:延迟
- eager:立即
-->
<collection property="emps"
select="com.mybatis.dao.EmployeeMapper.getEmpsByDeptId"
column="{deptId=id}" fetchType="lazy"/>
</resultMap> <select id="getDeptByIdWithEmpStep" resultMap="MyDeptStep">
select id,dept_name departmentName from tbl_dept where id=#{id}
</select>
</mapper>

Mybatis学习笔记8 - resultMap自定义结果集映射规则的更多相关文章

  1. MyBatis学习笔记之resultMap

    使用mybatis不能不说的是resultMap 相比resultClass来说resultMap可以适应更复杂的关系映射,允许指定字段的数据类型,支持“select *” ,并不要求定义 Resul ...

  2. Mybatis3.0-[tp_28-29]-映射文件-resultMap_自定义结果集映射规则_及关联环境的搭建

    笔记要点出错分析与总结工程组织 1.定义接口  EmployeeMapperPlus.java package com.dao; import com.bean.*; public interface ...

  3. MyBatis:学习笔记(3)——关联查询

    MyBatis:学习笔记(3)--关联查询 关联查询 理解联结 SQL最强大的功能之一在于我们可以在数据查询的执行中可以使用联结,来将多个表中的数据作为整体进行筛选. 模拟一个简单的在线商品购物系统, ...

  4. Mybatis学习笔记二

    本篇内容,紧接上一篇内容Mybatis学习笔记一 输入映射和输出映射 传递简单类型和pojo类型上篇已介绍过,下面介绍一下包装类型. 传递pojo包装对象 开发中通过可以使用pojo传递查询条件.查询 ...

  5. mybatis学习笔记--常见的错误

    原文来自:<mybatis学习笔记--常见的错误> 昨天刚学了下mybatis,用的是3.2.2的版本,在使用过程中遇到了些小问题,现总结如下,会不断更新. 1.没有在configurat ...

  6. Mybatis学习笔记导航

    Mybatis小白快速入门 简介 本人是一个Java学习者,最近才开始在博客园上分享自己的学习经验,同时帮助那些想要学习的uu们,相关学习视频在小破站的狂神说,狂神真的是我学习到现在觉得最GAN的老师 ...

  7. Mybatis学习笔记之二(动态mapper开发和spring-mybatis整合)

    一.输入映射和输出映射 1.1 parameterType(输入类型) [传递简单类型] 详情参考Mybatis学习笔记之一(环境搭建和入门案例介绍) 使用#{}占位符,或者${}进行sql拼接. [ ...

  8. mybatis学习笔记(10)-一对一查询

    mybatis学习笔记(10)-一对一查询 标签: mybatis mybatis学习笔记10-一对一查询 resultType实现 resultMap实现 resultType和resultMap实 ...

  9. mybatis学习笔记之基础复习(3)

    mybatis学习笔记之基础复习(3) mybatis是什么? mybatis是一个持久层框架,mybatis是一个不完全的ORM框架.sql语句需要程序员自己编写, 但是mybatis也是有映射(输 ...

随机推荐

  1. Luogu 3466 [POI2008]KLO-Building blocks

    BZOJ 1112. 题意相当于在一个长度为$k$的区间内选择一个数$s$使$\sum_{i = 1}^{k}\left | a_i - s \right |$最小. 很显然是中位数. 然后只要写一个 ...

  2. 10.model/view实例(4)

    任务:给表单的每一列添加列名. 思考: 1.只需要添加一个函数 headerData(). 横向方面添加列名 代码如下: QVariant MyModel::headerData(int sectio ...

  3. Spring第六篇---AOP

    接着Spring第五篇讲 我们今天将叙述以下几个知识点 1 什么是AOP AOP 是一种思想  横向重复  纵向抽取 在软件业,AOP为Aspect Oriented Programming的缩写,意 ...

  4. I - 一次元リバーシ / 1D Reversi(水题)

    Problem Statement Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is playe ...

  5. 给label添加点击事件

    后台代码: lb1.Attributes.Add("onclick", "getSN('" + lb1.Text.Trim() + "')" ...

  6. hdu2328(后缀数组 + 二分)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=2328 题意: 求 n 个串的字典序最小的最长公共子串 思路: 本题中单个字符串长度不超过 200, ...

  7. powershell 操作sharepoint命令集

    打开SharePoint 2013 Management Shell, and then run as administrator.执行如下命令 1. 添加wsp和安装Add-SPSolution - ...

  8. IdentityServer4 学习笔记[2]-用户名密码验证

    回顾 上一篇介绍了IdentityServer4客户端授权的方式,今天来看看IdentityServer4的基于密码验证的方式,与客户端验证相比,主要是配置文件调整一下,让我们来看一下 配置修改 pu ...

  9. libxml2 安装及使用

    https://gitlab.gnome.org/GNOME/libxml2/ ftp://xmlsoft.org/libxml2/libxml2-2.9.1.tar.gz /configuremak ...

  10. POJ1060 Modular multiplication of polynomials

    题目来源:http://poj.org/problem?id=1060 题目大意: 考虑系数为0和1的多项式.两个多项式的加法可以通过把相应次数项的系数相加而实现.但此处我们用模2加法来计算系数之和. ...