一、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. VS2012,更新补丁后--创建项目未找到与约束匹配的导出

    更新过一次漏洞,后来尝试建立一个项目,结果错误终于暴露了,创建项目时无法成功创建,而且提示:未找到与约束ontractNameMicrosoft.VisualStudio.Text.ITextDocu ...

  2. 阿里云ECS centos7.2 支持IPv6

    公司的项目因为服务器没有支持IPv6而被appstore给退回来了 第一部分 第一步:编辑 /etc/sysctl.conf 文件,将其中三条禁用IPv6的设置更改为: 第二步:使用命令启动启用IPv ...

  3. code manager toos TotoiseSVN解锁

    TotoiseSVN解锁 一.出现的原因: 1.是开发人员手动锁定了. 2.是由于版本错乱造成的锁定. 二.解决方案: 1.使用客户端解决方案: (1)删除本地副本,重新获取文件. (2)可以先尝试c ...

  4. Kotlin 数据类型(数值类型)

    Kotlin 的常见数据类型: 类型 范围 byte -128~127 short 32767-32768 int -2147483648~2147483647 long 92233720368547 ...

  5. Use Vim as a Python IDE

    Use Vim as a Python IDE I love vim and often use it to write Python code. Here are some useful plugi ...

  6. delay JS延迟执行

    window.onscroll = function () {    throttle(trrigerAdd,window);};function trrigerAdd(){    var $dHei ...

  7. CF525E Anya and Cubes(meet in the middle)

    题面 给你\(n\)个数,\(n\le 26\)初始序列为\(a_i,0\le a_i\le 10^9\) 你有\(k\)个\(!\),每个\(!\)可以使序列中的一个数变成\(a_i!\) 例如\( ...

  8. Python发送邮件代码

    Python发送带附件的邮件代码 #coding: utf-8 import smtplib import sys import datetime from email.mime.text impor ...

  9. P4014 分配问题

    \(\color{#0066ff}{题目描述}\) 有 \(n\) 件工作要分配给 \(n\) 个人做.第 \(i\) 个人做第 \(j\) 件工作产生的效益为 \(c_{ij}\) .试设计一个将 ...

  10. Linux(ubuntu)下固定IP的方法

    写在前面,问:为什么要固定ip.答:要知道固定IP的好处多多,随意搬动,固定共享地址,不怕断网等等 首先,我们要选取一个局域网内的IP,方法如下: 1.选取IP号段,一般是路由器DCHP以外的IP地址 ...