mybatis 使用resultMap实现表间关联
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实现表间关联的更多相关文章
- mybatis 使用auto mapping原理实现表间关联
Auto mapping的示例 数据库中有一个person表,结构如下: mysql> desc person; +-------+-------------+------+-----+---- ...
- MongoDB里做表间关联
MongoDB与关系型数据库的建模还是有许多不同,因为MongoDB支持内嵌对象和数组类型.MongoDB建模有两种方式,一种是内嵌(Embed),另一种是连接(Link).那么何时Embed何时Li ...
- Mybatis框架学习总结-表的关联查询
一对一关联 创建表和数据:创建一张教师表和班级表,这里假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关系. CREATE TABLE teacher( t_id INT PRIM ...
- MyBatis学习(二)---数据表之间关联
想要了解MyBatis基础的朋友可以通过传送门: MyBatis学习(一)---配置文件,Mapper接口和动态SQL http://www.cnblogs.com/ghq120/p/8322302. ...
- 【Mybatis】MyBatis之表的关联查询(五)
本章介绍Mybatis之表的关联查询 一对一关联 查询员工信息以及员工的部门信息 1.准备表employee员工表,department部门表 CREATE TABLE `employee` ( `i ...
- MyBatis入门程序之表关联
一.一对一查询(ResultType比较简单,只需要指向扩展的类:ResultMap逐个匹配比较麻烦,可以配置属性autoMapping="true",还可以可以实现延迟加载) 1 ...
- mysql 常用命令 | 表间 弱关联 join
show databases; use mhxy; select database(); show tables; desc account_list_175; ),(); select from_u ...
- Mybatis中的多表查询 多对多
示例:用户和角色 一个用户可以有多个角色 一个角色可以赋予多个用户 步骤: 1.建立两张表:用户表,角色表 让用户表和角色表具有多对多的关系. 需要使用中间表,中间表中包含各自的主键,在中间表中是外键 ...
- Mybatis的ResultMap的使用
本篇文章通过一个实际工作中遇到的例子开始吧: 工程使用Spring+Mybatis+Mysql开发.具体的业务逻辑很重,对象之间一层一层的嵌套.和数据库表对应的是大量的model类,而和前端交互的是V ...
随机推荐
- Flask的请求处理机制
在Flask的官方文档中是这样介绍Flask的: 对于Web应用,与客户端发送给服务器的数据交互至关重要.在Flask中由全局的request对象来提供这些信息 属性介绍 request.method ...
- 第1章 背景 - Identity Server 4 中文文档(v1.0.0)
大多数现代应用程序或多或少看起来像这样: 最常见的互动是: 浏览器与Web应用程序通信 Web应用程序与Web API进行通信(Web应用程序自身 或 代表用户 与 Web API 通信) 基于浏览器 ...
- 命令别名设置: alias, unalias
别名命令:alias 命令别名是一个很有趣的东西,特别是你的惯用指令特别长的时候!还有, 增设默认的选项在一些惯用的指令上面,可以预防一些不小心误杀文件的情况发生的时候! 举个例子来说,如果你要查询隐 ...
- 程序员50题(JS版本)(五)
程序21:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和. var arr=[]; var count=20; for(var i=0;i<= ...
- iOS----------弹窗动画
- (void)animationAlert:(UIView *)view { CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation ani ...
- 虹软2.0 离线人脸识别 Android 开发 Demo
环境要求1.运行环境 armeabi-v7a2.系统要求 Android 5.0 (API Level 21)及以上3.开发环境 Android Studio 下载地址:https://github. ...
- vs文件上传失败--超过最大字符限制
一.问题 在文件上传时,会遇到大文件上传失败. >F12查看报错网络请求返回结果 >问题分析 由于vs上传文件默认的字符大小控制. 二.解决方法 >在web.config中修改或添加 ...
- DVWA 黑客攻防演练(九) SQL 盲注 SQL Injection (Blind)
上一篇文章谈及了 dvwa 中的SQL注入攻击,而这篇和上一篇内容很像,都是关于SQL注入攻击.和上一篇相比,上一篇的注入成功就马上得到所有用户的信息,这部分页面上不会返回一些很明显的信息供你调试,就 ...
- Vue一个案例引发「内容分发slot」的最全总结
今天我们继续来说说 Vue,目前一直在自学 Vue 然后也开始做一个项目实战,我一直认为在实战中去发现问题然后解决问题的学习方式是最好的,所以我在学习一些 Vue 的理论之后,就开始自己利用业余时间做 ...
- ASP.NET Core 入门教程 10、ASP.NET Core 日志记录(NLog)入门
一.前言 1.本教程主要内容 ASP.NET Core + 内置日志组件记录控制台日志 ASP.NET Core + NLog 按天记录本地日志 ASP.NET Core + NLog 将日志按自定义 ...