AutoMapping

  auto mapping,直译过来就是自动映射,工作原理大概如下:

  假设我们有一张表,表名为person,包含id,name,age,addr这4个字段

mysql> desc person;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(30) | NO | | NULL | |
| age | int(2) | NO | | NULL | |
| addr | varchar(30) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+

  

  同时我们会创建一个实体类Person来与这张person表进行对应,此时Person类的属性名称和person表中的字段名称一一对应,不仅是名称对应,数据类型也是一一对应的:

package lixin.gan.pojo;

public class Person {

	private int id;
private String name;
private int age;
private String addr; // 省略了构造方法、setter、getter、toString
}

    

  之后我们会创建PersonMapper.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="lixin.gan.mapper.PersonMapper">
<select id="selectAll" resultType="lixin.gan.pojo.Person">
select * from person
</select>
</mapper>

  注意上面的resultType,这里的resultType已经指明了返回值的类型,于是mybatis在从结果集中取出一条数据后,会将每一行记录的字段名,对应到Person类的同名属性,将字段值赋值给Person类的同名属性。

  此时需要注意:如果从person表中查询数据,取出结果集中的字段名称,和Person类中的属性值对应不上(名称不相同),那么返回的Person类的对象对应的那个属性就会设置为null。举个例子,person表中的name字段,应该auto mapping到Person类的name属性,但如果,Person类中,没有name属性,却有一个name1属性,那么再返回结果的时候,name1属性就会初始为null。

  虽然resultType很方便,可以自动的实现映射,但是,我们往往需要进行自定义的映射,此时就可以使用resultMap了。

使用resultMap实现单表映射

  假设实体类中Person.java的属性更改如下:

package lixin.gan.pojo;

public class Person {

	private int id1;
private String name1;
private int age1;
private String addr1; // 省略了构造方法、setter、getter、toString
}

  

  要想使用mybatis时,person表的字段仍能正确对应到Person类中的准确字段中,使用resultMap来指定对应关系,可以这样做:

<?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="lixin.gan.mapper.PersonMapper"> <!-- 定义数据表中的字段,与实体类中的属性对应关系 -->
<resultMap type="lixin.gan.pojo.Person" id="testResultMap">
<!-- 数据表中的主键列字段使用<id />标签, 其他字段使用<result />标签 -->
<!-- column表示的是数据表中的字段, property表示的是实体类中对应的属性 -->
<id column="id" property="id1" />
<result column="name" property="name1" />
<result column="age" property="age1" />
<result column="addr" property="addr1" />
</resultMap> <!-- 此时不用resultType属性,而是使用resultMap属性,属性值就是前面定义的对应关系id -->
<select id="selectAll" resultMap="testResultMap">
select * from person
</select>
</mapper>

  

使用resultMap实现n+1查询

  n+1查询是指:先查询出某个表的全部信息,然后根据这个表的信息,去查询另外一个表的信息。

  举下面一个例子:查询student表后,根据student表中的tid,查询对应的teacher表中信息。

  Teacher类(对应teacher表),实体类定义如下:

package lixin.gan.pojo;

public class Teacher {
private int id;
private String name; // 省略了构造方法、setter、getter、toString
}

  

  TeacherMapper.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="lixin.gan.mapper.TeacherMapper"> <resultMap type="lixin.gan.pojo.Teacher" id="teacherMap">
<id column="id" property="id" />
<result column="name" property="name" />
</resultMap> <select id="selectAllTeacher" resultMap="teacherMap">
select * from teacher
</select> <select id="selectTeacherById" resultType="teacher" parameterType="int">
select * from teacher where id=#{0}
</select>
</mapper>

  

  现在有一个Student类(对应student表),实体类定义如下:

package lixin.gan.pojo;

public class Student {
private int id; // 学生id
private int age; // 学生年龄
private String name;// 学生姓名
private int tid; // 老师的id
private Teacher teacher; // 包含一个Teacher对象
// 省略了构造方法、setter、getter、toString
}

  与此同时,StudentMapper.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="lixin.gan.mapper.StudentMapper"> <!-- 定义数据表中的字段,与实体类中的属性对应关系 -->
<resultMap type="lixin.gan.pojo.Student" id="studentMap">
<id column="id" property="id" /> <result column="name" property="name" />
<result column="age" property="age" />
<result column="tid" property="tid" /> <!-- 如果当前xml对应的实体类中包含一个类对象,那么可以使用association标签来进行关联 -->
<!-- property仍旧指的是实体类中的属性名,select表示要为该属性赋值,需要执行的查询操作(id),column表示传入的参数-->
<association
property="teacher"
select="lixin.gan.mapper.TeacherMapper.selectTeacherById"
column="tid"
></association> <!-- 如果当前的xml对应的实体来中包含一个容器集合,那么可以使用collection标签来进行关联 -->
<!-- <collection property=""></collection> -->
</resultMap> <select id="selectAllStudent" resultMap="studentMap">
select * from student
</select>
</mapper>

  

  测试代码:

package lixin.gan.test;

import java.io.InputStream;
import java.util.List; 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 lixin.gan.pojo.Student; public class Test {
public static void main(String[] args) throws Exception{
InputStream config = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config); SqlSession session = factory.openSession(); List<Student> list = session.selectList("lixin.gan.mapper.StudentMapper.selectAllStudent"); for (Student stu : list) {
System.out.println(stu);
}
}
}

  运行结果,打印log4j日志:

==>  Preparing: select * from student
==> Parameters:
====> Preparing: select * from teacher where id=?
====> Parameters: 2(Integer)
<==== Total: 1
====> Preparing: select * from teacher where id=?
====> Parameters: 1(Integer)
<==== Total: 1
====> Preparing: select * from teacher where id=?
====> Parameters: 5(Integer)
<==== Total: 1
====> Preparing: select * from teacher where id=?
====> Parameters: 4(Integer)
<==== Total: 1
<== Total: 4
Student [id=1, age=5, name=张三, tid=2, teacher=Teacher [id=2, name=黄老师]]
Student [id=2, age=10, name=李四, tid=1, teacher=Teacher [id=1, name=李老师]]
Student [id=3, age=25, name=王五, tid=5, teacher=Teacher [id=5, name=方老师]]
Student [id=4, age=30, name=赵六, tid=4, teacher=Teacher [id=4, name=蔡老师]]

  

使用resultMap关联集合对象

  关联集合对象,可以理解为,一个类A的某个属性,是包含另一个类B的集合。

  举例:一个老师有多个学生,查询所有老师,并且查出老师的学生。

  Student.java实体类如下:

package lixin.gan.pojo;

public class Student {
private int id; // 学生id
private int age; // 学生年龄
private String name;// 学生姓名
private int tid; // 老师的id // 省略了构造方法,setter、getter、toString
}

  对应的StudentMapper.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="lixin.gan.mapper.StudentMapper">
<select id="selectStudentById" resultType="lixin.gan.pojo.Student">
select * from student where tid=#{0}
</select>
</mapper>

  

  Teacher.java实体类内容如下:

package lixin.gan.pojo;

import java.util.List;

public class Teacher {
private int id;
private String name; private List<Student> list; // 省略了构造方法,setter、getter、toString
}

  TeacherMapper.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="lixin.gan.mapper.TeacherMapper"> <resultMap type="lixin.gan.pojo.Teacher" id="teacherMap">
<id column="id" property="id" />
<result column="name" property="name" /> <!-- 当关联的类型是集合类型,那么就需要使用collection标签,并且要指定ofType,表示集合中元素的值 -->
<collection
property="list"
select="lixin.gan.mapper.StudentMapper.selectStudentById"
ofType="lixin.gan.pojo.Student"
column="id"
></collection>
</resultMap> <select id="selectAllTeacher" resultMap="teacherMap">
select * from teacher
</select> </mapper>

  

  运行测试代码:

package lixin.gan.test;

import java.io.InputStream;
import java.util.List; 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 lixin.gan.pojo.Teacher; public class Test {
public static void main(String[] args) throws Exception{
InputStream config = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config); SqlSession session = factory.openSession(); List<Teacher> list = session.selectList("lixin.gan.mapper.TeacherMapper.selectAllTeacher"); for (Teacher teacher : list) {
System.out.println(teacher);
}
}
}

  

  利用log4j打印的日志,以及程序运行输出如下:

==>  Preparing: select * from teacher
==> Parameters:
====> Preparing: select * from student where tid=?
====> Parameters: 1(Integer)
<==== Total: 1
====> Preparing: select * from student where tid=?
====> Parameters: 2(Integer)
<==== Total: 3
====> Preparing: select * from student where tid=?
====> Parameters: 3(Integer)
<==== Total: 0
====> Preparing: select * from student where tid=?
====> Parameters: 4(Integer)
<==== Total: 2
====> Preparing: select * from student where tid=?
====> Parameters: 5(Integer)
<==== Total: 1
<== Total: 5
Teacher [id=1, name=李老师, list=[Student [id=2, age=10, name=李四, tid=1]]]
Teacher [id=2, name=黄老师, list=[Student [id=1, age=5, name=张三, tid=2], Student [id=5, age=22, name=小红, tid=2], Student [id=6, age=23, name=小花, tid=2]]]
Teacher [id=3, name=王老师, list=[]]
Teacher [id=4, name=蔡老师, list=[Student [id=4, age=30, name=赵六, tid=4], Student [id=7, age=30, name=小黄, tid=4]]]
Teacher [id=5, name=方老师, list=[Student [id=3, age=25, name=王五, tid=5]]]

  

  

mybatis 使用resultMap实现表间关联的更多相关文章

  1. mybatis 使用auto mapping原理实现表间关联

    Auto mapping的示例 数据库中有一个person表,结构如下: mysql> desc person; +-------+-------------+------+-----+---- ...

  2. MongoDB里做表间关联

    MongoDB与关系型数据库的建模还是有许多不同,因为MongoDB支持内嵌对象和数组类型.MongoDB建模有两种方式,一种是内嵌(Embed),另一种是连接(Link).那么何时Embed何时Li ...

  3. Mybatis框架学习总结-表的关联查询

    一对一关联 创建表和数据:创建一张教师表和班级表,这里假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关系. CREATE TABLE teacher( t_id INT PRIM ...

  4. MyBatis学习(二)---数据表之间关联

    想要了解MyBatis基础的朋友可以通过传送门: MyBatis学习(一)---配置文件,Mapper接口和动态SQL http://www.cnblogs.com/ghq120/p/8322302. ...

  5. 【Mybatis】MyBatis之表的关联查询(五)

    本章介绍Mybatis之表的关联查询 一对一关联 查询员工信息以及员工的部门信息 1.准备表employee员工表,department部门表 CREATE TABLE `employee` ( `i ...

  6. MyBatis入门程序之表关联

    一.一对一查询(ResultType比较简单,只需要指向扩展的类:ResultMap逐个匹配比较麻烦,可以配置属性autoMapping="true",还可以可以实现延迟加载) 1 ...

  7. mysql 常用命令 | 表间 弱关联 join

    show databases; use mhxy; select database(); show tables; desc account_list_175; ),(); select from_u ...

  8. Mybatis中的多表查询 多对多

    示例:用户和角色 一个用户可以有多个角色 一个角色可以赋予多个用户 步骤: 1.建立两张表:用户表,角色表 让用户表和角色表具有多对多的关系. 需要使用中间表,中间表中包含各自的主键,在中间表中是外键 ...

  9. Mybatis的ResultMap的使用

    本篇文章通过一个实际工作中遇到的例子开始吧: 工程使用Spring+Mybatis+Mysql开发.具体的业务逻辑很重,对象之间一层一层的嵌套.和数据库表对应的是大量的model类,而和前端交互的是V ...

随机推荐

  1. 第25章 退出外部身份提供商 - Identity Server 4 中文文档(v1.0.0)

    当用户注销 IdentityServer并且他们使用外部身份提供程序登录时,可能会将其重定向到注销外部提供程序.并非所有外部提供商都支持注销,因为它取决于它们支持的协议和功能. 要检测是否必须将用户重 ...

  2. 《C#并发编程经典实例》学习笔记—2.4 等待一组任务完成

    问题 执行几个任务,等待它们全部完成. 使用场景 几个独立任务需要同时进行 UI界面加载多个模块,并发请求 解决方案 Task.WhenAll 传入若干任务,当所有任务完成时,返回一个完成的任务. 重 ...

  3. [转]nodeJs--koa2 REST API

    本文转自:https://blog.csdn.net/davidPan1234/article/details/83413958 REST API规范编写REST API,实际上就是编写处理HTTP请 ...

  4. Java开发笔记(二十九)大整数BigInteger

    早期的编程语言为了节约计算机的内存,给数字变量定义了各种存储规格的数值类型,比如字节型byte只占用一个字节大小,短整型short占用两个字节大小,整型int占用四个字节大小,长整型long占用八个字 ...

  5. Vue利用canvas实现移动端手写板

    <template> <div class="hello"> <!--touchstart,touchmove,touchend,touchcance ...

  6. 网络最大流算法—最高标号预流推进HLPP

    吐槽 这个算法.. 怎么说........ 学来也就是装装13吧.... 长得比EK丑 跑的比EK慢 写着比EK难 思想 大家先来猜一下这个算法的思想吧:joy: 看看人家的名字——最高标号预留推进 ...

  7. 【Vue 2.x】计算属性

    Vue对象,按照现在的学习进度,可以分为: 其中el代表作用的HTML元素: data代表el中的所有数据: methods代表el中所有元素上的事件: computed代表计算属性,用于计算data ...

  8. SuperMap -WebGL 实现地球的背景透明并显示自定义图片

    实现效果如图: 实现代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset ...

  9. C#中的yield return用法演示源码

    下边代码段是关于C#中的yield return用法演示的代码. using System;using System.Collections;using System.Collections.Gene ...

  10. 微信小程序(五) 利用模板动态加载数据

    利用模板动态加载数据,其实是对上一节静态数据替换成动态数据: