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. 网络流量状态命令总结 (含notp安装)

    1. sar -n DEV 1 2 sar命令包含在sysstat工具包中,提供系统的众多统计数据.其在不同的系统上命令有些差异,某些系统提供的sar支持基于网络接口的数据统计,也可以查看设备上每秒收 ...

  2. Robust Real-time Object Detection学习

    健壮实时对象检测(robust real-time object detection) 高检测率(high detection rates), 一种新的图像表示方法,叫做积分图(integral im ...

  3. Luogu P2661 信息传递

    传送门 一眼就能看出来是个并查集 但是并不会写... 看了一下题解说是并查集求最小环qwq 所以,每次加入第i个小同学,判断如果他要告诉的小同学k最后会告诉他(也就是转回来了), 就说明出现了一个环, ...

  4. kubernetes session回话保持

    1.Nginx 版本 root@ingress-nginx-controller-4b75b:/# /usr/sbin/nginx -vnginx version: nginx/1.13.9 2.in ...

  5. IIS导入.pfx证书时报错:"A specified logon session does not exist. It may already have been terminated."

    在IIS中可以直接导入.pfx文件来给站点绑定https协议: 如果在导入.pfx文件时,不选择"Allow this certificate to be exported"的话 ...

  6. ansible环境部署及常用模块总结 - 运维笔记

    一.  Ansible 介绍Ansible是一个配置管理系统configuration management system, python 语言是运维人员必须会的语言, ansible 是一个基于py ...

  7. Week 7 迭代总结

    写在前面: 本次我为团队博客写了一篇总结,深刻总结了我们组发生的问题以及将来要做的事情.有兴趣请移步http://www.cnblogs.com/Buaa-software Week 7 Alpha轮 ...

  8. Linux内核分析— —进程的切换和系统的一般执行过程

    进程调度的时机 linux进程调度是基于分时和优先级的 中断处理过程(包括时钟中断.I/O中断.系统调用和异常)中,直接调用schedule(),或者返回用户态时根据need_resched标记调用s ...

  9. JavaScript —— 数组

    Array方法 1.查找元素 indexOf()用来查找传进来的参数在目标数组中是否存在.如果目标数组包含该参数,就返回该元素在数组中的索引:如果不包含,就返回-1. 如果数组中包含多个相同的元素,i ...

  10. text2

    我的实践2代码已经传到GITHUb:https://github.com/jiaweihao/Test.git一下为测试结果截图: