前言

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

搭建开发环境

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

 CREATE TABLE [dbo].[t_teacher](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](30) NULL,
[title] [nvarchar](30) NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] GO
 CREATE TABLE [dbo].[t_student](
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](30) NULL,
[major] [nvarchar](30) NULL,
[supervisor_id] [int] NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

一对一关联查询

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

 <?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.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" javaType="Teacher">
<id property="id" column="t_id" />
<result property="name" column="t_name"/>
<result property="title" column="title"/>
</association>
</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>

teacher model

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

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;
}
}

  

单元测试

@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从入门到放弃三:一对一关联查询 前言 简单来说在mybatis.xml中实现关联查询实在是有些麻烦,正是因为起框架本质是实现orm的半自动化. 那么mybatis实现一对一的关联查询则是 ...

  2. MyBatis从入门到放弃四:一对多关联查询

    前言 上篇学习了一对一关联查询,这篇我们学习一对多关联查询.一对多关联查询关键点则依然是配置resultMap,在resultMap中配置collection属性,别忽略了ofType属性. 搭建开发 ...

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

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

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

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

  5. mybatis 使用接口增删改查和两表一对一关联查询

    导包 总配置文件 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration ...

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

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

  7. MyBatis关联查询,一对一关联查询

    数据库E-R关系 实体类 public class City { Long id; String name; Long countryId; Date lastUpdate; } public cla ...

  8. mybatis的动态sql编写以及一对一关系查询和一对多的查询

    创建mybatis数据库,运行以下sql语句 /* SQLyog Ultimate v8.32 MySQL - 5.5.27 : Database - mybatis **************** ...

  9. 一对一关联查询时使用relation连贯操作查询后,调用getLastSql()方法输出的sql语句

    如题: 一对一关联查询时使用relation连贯操作查询后,调用getLastSql()方法输出的sql语句不是一条关联查询语句. 例如: $list = $db->relation(true) ...

随机推荐

  1. Zookeeper系列3 实现分布式锁

    基本思路 1 client调用create()方法创建“/locks/_lock_”临时顺序节点,注意节点类型是EPHEMERAL_SEQUENTIAL 2 client调用getChildren(& ...

  2. file 上传大小限制问题

    今天突然传了一张很大的图片 结果怎么传都获取不到信息(如下); 最后查看了下php.ini 中的 " upload_max_filesize  "最大只允许了2M!  改下就可以 ...

  3. vue路由跳转到指定页面

    1.this.$router.push({name:'Home'}) 2.this.$router.push({path:'/view'}) 3.this.$router.replace({name: ...

  4. Codeforces Round #546 (Div. 2) E 推公式 + 线段树

    https://codeforces.com/contest/1136/problem/E 题意 给你一个有n个数字的a数组,一个有n-1个数字的k数组,两种操作: 1.将a[i]+x,假如a[i]+ ...

  5. QT在Linux下的安装

    QT是一个跨平台的C++开发库,设计思想是同样的,C++无需修改就可以在windows.linux.macOS等平台上使用,他使开发更专注于构建软件的核心价值,而不是维护API.作为面向对象的框架,它 ...

  6. fork()函数、进程表示符、进程位置

    linux.centos6.5 fork()函数:作用于创建子进程.返回值有两个,一个是向父进程返回它的pid,一个是返回0: eg1: #include<stdio.h> #includ ...

  7. Dynamic Programming | Set 1 (Overlapping Subproblems Property)

    动态规划是这样一种算法范式:将复杂问题划分为子问题来求解,并且将子问题的结果保存下来以避免重复计算.如果一个问题拥有以下两种性质,则建议使用动态规划来求解. 1 重叠子问题(Overlapping S ...

  8. win7安装vs2017时闪退

    最近用公司的笔记本电脑,装win10发现太卡,无奈最终选择安装win7系统,本以为系统安装成功了,接下来只要安装下开发环境:vs2017 sqlserver等就好,结果在安装vs2017的时候,一直出 ...

  9. 基于vue的颜色选择器vue-color-picker

    项目中有用到颜色选择器的童鞋们可以看过来了 关于color-picker的jquery的插件是有蛮多,不过vue组件没有吧,反正我没有找到, 虽然element-ui里面有这个,但是你愿意为了一个小功 ...

  10. 如何设置 sass 全局变量,js如何使用 sass 变量

    关键词:sass全局变量 js引用sass变量 1 如何在样式中使用 scss 的声明的全局变量 假设我们有一个全局的 scss 变量文件/styles/_vars.sass,如下: $red: re ...