MyBatis从入门到放弃三:一对一关联查询

前言

简单来说在mybatis.xml中实现关联查询实在是有些麻烦,正是因为起框架本质是实现orm的半自动化。 那么mybatis实现一对一的关联查询则是使用association属性和resultMap属性。

搭建开发环境

创建student表、teacher表来搭建一对一的关联查询场景,student表添加外键supervisor_id实现和teacher表的关联

 1 CREATE TABLE [dbo].[t_teacher](
2 [id] [int] IDENTITY(1,1) NOT NULL,
3 [name] [nvarchar](30) NULL,
4 [title] [nvarchar](30) NULL,
5 PRIMARY KEY CLUSTERED
6 (
7 [id] ASC
8 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
9 ) ON [PRIMARY]
10
11 GO
 1 CREATE TABLE [dbo].[t_student](
2 [id] [int] IDENTITY(1,1) NOT NULL,
3 [name] [nvarchar](30) NULL,
4 [major] [nvarchar](30) NULL,
5 [supervisor_id] [int] NULL,
6 PRIMARY KEY CLUSTERED
7 (
8 [id] ASC
9 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
10 ) ON [PRIMARY]

一对一关联查询

一对一关联的关键是在mapper.xml中创建resultMap。  如下代码看到了在studentResultMap中添加了属性association,property是在model类中的外键属性名称,别忘记指定JavaType

 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="com.autohome.mapper.Student">
6 <resultMap id="studentResultMap" type="Student">
7 <id property="id" column="id"/>
8 <result property="name" column="name"/>
9 <result property="major" column="major"/>
10 <association property="supervisor" javaType="Teacher">
11 <id property="id" column="t_id" />
12 <result property="name" column="t_name"/>
13 <result property="title" column="title"/>
14 </association>
15 </resultMap>
16
17
18 <select id="getStudentById" parameterType="int" resultMap="studentResultMap">
19 SELECT st.id,st.name,st.major,
20 t.id t_id,t.name t_name,t.title
21 FROM t_student st inner join t_teacher t on st.supervisor_id=t.id
22 where st.id=#{id}
23 </select>
24 </mapper>

teacher model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Teacher {
    private int id;
    private String name;
    private String title;
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
        this.title = title;
    }
}

student model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class Student {
    private int id;
    private String name;
    private String major;
 
    private Teacher supervisor;
 
    public Teacher getSupervisor() {
        return supervisor;
    }
 
    public void setSupervisor(Teacher supervisor) {
        this.supervisor = supervisor;
    }
 
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getMajor() {
        return major;
    }
 
    public void setMajor(String major) {
        this.major = major;
    }
}

  

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
    public void getStudentById(){
        SqlSession sqlSession=null;
        try{
            sqlSession=sqlSessionFactory.openSession();
 
            Student student = sqlSession.selectOne("com.autohome.mapper.Student.getStudentById",1);
            System.out.println("id:"+student.getId()+",name:"+student.getName()+",导师姓名:"+student.getSupervisor().getName()+",导师职称:"+student.getSupervisor().getTitle());
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }

附实现截图

嵌套resultMap

如上的resultmap用起来总是不方便的,万一后续再到其他关联查询需要用到teacher表呢,那么我们把teacherResultMap单独拿出来,不仅是resultMap可以嵌套,sql语句也可以嵌套。

分别创建studentResultMap和suprvisorResultMap。后在studentResultMap的association中使用resultMap引用supervisorResultMap。

<mapper namespace="com.autohome.mapper.Student">

    <resultMap id="studentResultMap" type="Student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="major" column="major"/>
<association property="supervisor" resultMap="suprvisorResultMap"/>
</resultMap> <resultMap id="suprvisorResultMap" type="Teacher">
<id property="id" column="t_id" />
<result property="name" column="t_name"/>
<result property="title" column="title"/>
</resultMap> <select id="getStudentById" parameterType="int" resultMap="studentResultMap">
SELECT st.id,st.name,st.major,
t.id t_id,t.name t_name,t.title
FROM t_student st inner join t_teacher t on st.supervisor_id=t.id
where st.id=#{id}
</select>
</mapper>

实现结果和上面相同。

MyBatis:一对一关联查询的更多相关文章

  1. MyBatis学习(四)MyBatis一对一关联查询

    一对一关联查询即.两张表通过外键进行关联.从而达到查询外键直接获得两张表的信息.本文基于业务拓展类的方式实现. 项目骨架 配置文件conf.xml和db.properties前几节讲过.这里就不细说了 ...

  2. mybatis一对一关联查询——(八)

    1.需求 查询所有订单信息,关联查询下单用户信息. 注意: 因为一个订单信息只会是一个人下的订单,所以从查询订单信息出发关联查询用户信息为一对一查询.如果从用户信息出发查询用户下的订单信息则为一对多查 ...

  3. Mybatis一对一关联查询

    有两张表,老师表teacher和班级表class,一个class班级对应一个teacher,一个teacher对应一个class 需求是根据班级id查询班级信息(带老师的信息) 创建teacher和c ...

  4. 五 Mybatis一对一关联查询的两种方式(基于resultType&基于resultMap)

    关联查询: 一个用户对应多个订单,一个订单只有一个用户 订单关联用户:两种方式 一:基于resultTYpe,一个与表关系一样的pojo实现 主表订单,从表用户 首先要有一个与关联查询表关系一样的po ...

  5. MyBatis 一对一关联查询

    xml文件: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC & ...

  6. Mybatis之关联查询

    一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创建表和数据 创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就是一种一对一的关 ...

  7. MyBatis从入门到放弃三:一对一关联查询

    前言 简单来说在mybatis.xml中实现关联查询实在是有些麻烦,正是因为起框架本质是实现orm的半自动化. 那么mybatis实现一对一的关联查询则是使用association属性和resultM ...

  8. Mybatis学习4——一对一关联查询方法2------实体作为属性

    实体order和user采用resultMap order package pojo; import java.util.Date; public class Order { private Inte ...

  9. Mybatis学习4——一对一关联查询方法1--创建实体

    创建一个实体继承两个实体之一,另一个实体作为属性 实体1. order package pojo; import java.util.Date; public class Order { privat ...

随机推荐

  1. PHP实现栈数据结构

    利用php面向对象思想,栈的属性有top.最大存储数.和存储容器(这里利用了php数组). 代码如下:实现了入栈.出栈.遍历栈的几个方法: <?php class Stack{ const MA ...

  2. python---pandas.merge使用

    merge 函数参数 ”’ merge: 合并数据集, 通过left, right确定连接字段,默认是两个数据集相同的字段 参数 说明 left 参与合并的左侧DataFrame right 参与合并 ...

  3. Luogu4697 CEOI2011 Balloons 单调栈

    传送门 题意:给出$N$个气球,从左往右给出它们的$x_i$与$r_i$.现在从左往右给它们充气,每一个气球在充气的过程中始终在$x_i$点与地面相切,且最大半径为$r_i$.如果在充气的过程中气球与 ...

  4. CF418D Big Problems for Organizers 树的直径、ST表

    题目传送门:http://codeforces.com/problemset/problem/418/D 大意:给出一棵有$N$个节点的树,所有树边边权为$1$,给出$M$次询问,每个询问给出$x,y ...

  5. 如何从现有版本1.4.8升级到element UI2.0.11

    现在的项目是定死的依赖以下几个核心组件的版本: vue 2.3.3 element-ui 1.4.8 vue-template-comiler 2.3.3 将以前定死的依赖修改为 vue ^2.3.3 ...

  6. JQuery将form表单值转换成json字符串函数

    由于后台接口限定,必须要将表单内容转换成json字符串提交,因此写了一个将form表单值转成json字符串的函数.     前提:页面引入了JQuery          下面直接上代码 一.代码 / ...

  7. 【SQL】四种排序开窗函数

    一 .简单了解什么是开窗函数 什么是开窗函数,开窗函数有什么作用,特征是什么? 所谓开窗函数就是定义一个行为列,简单讲,就是在你查询的结果上,直接多出一列值(可以是聚合值或是排序号),特征就是带有ov ...

  8. Caffe源码中math_functions文件分析

    Caffe源码(caffe version:09868ac , date: 2015.08.15)中有一些重要文件,这里介绍下math_functions文件. 1.      include文件: ...

  9. 分布式系统session一致性的问题

    session的概念 什么是session? 服务器为每个用户创建一个会话,存储用户的相关信息,以便多次请求能够定位到同一个上下文.这样,当用户在应用程序的 Web 页之间跳转时,存储在 Sessio ...

  10. Linux系统入门教程:如何在 Linux 中修改默认的 Java 版本

    提问:当我尝试在Linux中运行一个Java程序时,我遇到了一个错误.看上去像程序编译所使用的Java版本与我本地的不同.我该如何在Linux上切换默认的Java版本? 当Java程序编译时,编译环境 ...