百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

网友都说MyBatis多表查询太难了,小白:就这?我都学会了

bigegpt 2024-08-01 11:49 13 浏览

该文章是介绍《MyBatis实现多表查询》,根据我以前的学习笔记以及工作中长时间积累所整理的一份笔记,纯干货,希望对大家有帮助。

MyBatis实现多表查询

一、多对一查询

数据库的准备

创建两张表,一张老师表,一张学生表

将老师主键id关联学生外键tid

创建sql的语句

create table teacher(
   id int  primary key,
	teacher_name varchar(30) not null
)
insert into teacher(id,teacher_name) values (1,'毛老师')
create table student(
  id int  primary key,
	student_name varchar(30) not null,
	tid int default null
)
//建立主外键关联
alter table student add constraint teacher_student_id foreign key (tid) references teacher(id)
insert into student values (1,'小明',1)
insert into student values (2,'小毛',1)
insert into student values (3,'小红',1)
insert into student values (4,'大黄',1)
insert into student values (5,'超儿',1)

项目结构

使用Lombok插件,创建实体类。
(提高整洁度,主要想toulan

@Data
public class Student {
    private int id;
    private String name;
    //学生需要关联一个老师
    private Teacher teacher;
}
@Data
public class Teacher {
    private int id;
    private String name;
}

二、嵌套查询处理

1.编写接口

public interface StudentMapper {
    //查询所有学生的信息以及对应老师的信息
    public List<Student> getStudent();
}

2. 编写StudentMapper.xml的查询语句(重点)

<mapper namespace="dao.StudentMapper">
<!--    思路:
        1. 查询所有学生的信息
        根据查询出来的学生tid,寻找对应的老师
-->
    <select id="getStudent" resultMap="StudentTeacher">
    select * from student
    </select>
    <resultMap id="StudentTeacher" type="pojo.Student">
<!--        复杂的属性需要单独处理 是对象就使用association,是集合就使用collection-->
<!--    select 的查询    -->
        <result property="name" column="student_name"/>
        <association property="teacher" column="tid" javaType="pojo.Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="pojo.Teacher">
        select * from teacher where id=#{id}
    </select>

3.测试类

@Test
    public void getStudent(){
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.getStudent();
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }

测试结果

三、联合查询处理

1.编写接口

//按照结果嵌套查询
public List<Student> getStudent2();

2. 编写StudentMapper.xml的查询语句(重点)

<!--    按照结果嵌套处理-->
    <select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.student_name sname,t.teacher_name tname
    from student s,teacher t
    where s.tid=t.id
    </select>
    <resultMap id="StudentTeacher2" type="pojo.Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="pojo.Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

3.编写测试类

@Test
    public void getStudent(){
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.getStudent2();
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }

测试结果

二、一对多查询

更改实体类

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
@Data
public class Teacher {
    private int id;
    private String name;
    //一个老师拥有多个学生
    private List<Student> students;
}

1、嵌套查询处理

1.编写接口

Teacher getTeacher2(@Param("tid") int id);
由于字段不一致,要做映射

2.主要TeacherMapper.xml的查询语句(重点)

<select id="getTeacher2" resultMap="TeacherStudent2">
            select * from teacher where id=#{tid}
    </select>
    <resultMap id="TeacherStudent2" type="pojo.Teacher">
        <result property="name" column="teacher_name"/>
        <collection property="students" javaType="ArrayList" ofType="pojo.Student" select="getStudentByTeacherId" column="id"/>
    </resultMap>
    <select id="getStudentByTeacherId" resultType="pojo.Student">
        select * from student where tid=#{tid}
    </select>

3.测试类

@Test
    public void getTeacher(){
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher2(1);
        System.out.println(teacher);
        sqlSession.close();
    }

测试结果:

Teacher(id=0, name=毛老师, students=[Student(id=1, name=null, tid=1), Student(id=2, name=null, tid=1), Student(id=3, name=null, tid=1), Student(id=4, name=null, tid=1), Student(id=5, name=null, tid=1)])

2、联合查询处理

1.编写接口

//获取指定老师下的所有学生及老师的信息
    Teacher getTeacher(@Param("tid") int id);
由于字段不一致,要做映射

2.主要TeacherMapper.xml的查询语句(重点)

<!--    按结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid,s.student_name sname,t.teacher_name tname,t.id tid
        from student s,teacher t
        where s.tid=t.id and t.id=#{tid}
    </select>
    <resultMap id="TeacherStudent" type="pojo.Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--        复杂的属性需要单独处理 是对象就使用association,是集合就使用collection
        javaType="" 指定的属性类型
        集合中的泛型信息,使用ofType获取-->
        <collection property="students" ofType="pojo.Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

3.测试类

@Test
    public void getTeacher(){
        SqlSession sqlSession = Mybatisutil.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }

测试结果:

Teacher(id=1, name=毛老师, students=[Student(id=1, name=小明, tid=1), Student(id=2, name=小毛, tid=1), Student(id=3, name=小红, tid=1), Student(id=4, name=大黄, tid=1), Student(id=5, name=超儿, tid=1)])

总结:

本章就使用了简单的两张表联合查询,介绍简单的使用,更复杂的多表联合主要在编写sql的时候难度大点,或者是嵌套查询要更严谨点
官方文档也给了详细的非常复杂的多表查询如下: mybatis,这么复杂的看得我头疼

<!-- 非常复杂的语句 -->
<select id="selectBlogDetails" resultMap="detailedBlogResultMap">
  select
       B.id as blog_id,
       B.title as blog_title,
       B.author_id as blog_author_id,
       A.id as author_id,
       A.username as author_username,
       A.password as author_password,
       A.email as author_email,
       A.bio as author_bio,
       A.favourite_section as author_favourite_section,
       P.id as post_id,
       P.blog_id as post_blog_id,
       P.author_id as post_author_id,
       P.created_on as post_created_on,
       P.section as post_section,
       P.subject as post_subject,
       P.draft as draft,
       P.body as post_body,
       C.id as comment_id,
       C.post_id as comment_post_id,
       C.name as comment_name,
       C.comment as comment_text,
       T.id as tag_id,
       T.name as tag_name
  from Blog B
       left outer join Author A on B.author_id = A.id
       left outer join Post P on B.id = P.blog_id
       left outer join Comment C on P.id = C.post_id
       left outer join Post_Tag PT on PT.post_id = P.id
       left outer join Tag T on PT.tag_id = T.id
  where B.id = #{id}
</select>

在我们编写的时候注意点:

1.不要忘记注册Mapper.xml

2.在初学的时候尽量不要给实体类取别名,为了不要混淆,加深理解

3.实体类字段要和数据库字段一致,如果不一致,那就要用result标签做映射

4.复杂的属性需要单独处理,是对象就使用association,是集合就使用collection来映射

javaType="" 指定的属性类型

集合中的泛型信息,使用ofType获取

多注意复杂属性的嵌套使用

JavaType & ofType

1.JavaType 用来指定实体类中属性的类型

2.ofType 用来指定映射到List或者集合中的实体类pojo类型,泛型中的约束类型

  • 以上就是《MyBatis实现多表查询》的分享
  • 也欢迎大家交流探讨,该文章若有不正确的地方,希望大家多多包涵。
  • 你们的支持就是我最大的动力,如果对大家有帮忙给个赞哦~~~

相关推荐

当Frida来“敲”门(frida是什么)

0x1渗透测试瓶颈目前,碰到越来越多的大客户都会将核心资产业务集中在统一的APP上,或者对自己比较重要的APP,如自己的主业务,办公APP进行加壳,流量加密,投入了很多精力在移动端的防护上。而现在挖...

服务端性能测试实战3-性能测试脚本开发

前言在前面的两篇文章中,我们分别介绍了性能测试的理论知识以及性能测试计划制定,本篇文章将重点介绍性能测试脚本开发。脚本开发将分为两个阶段:阶段一:了解各个接口的入参、出参,使用Python代码模拟前端...

Springboot整合Apache Ftpserver拓展功能及业务讲解(三)

今日分享每天分享技术实战干货,技术在于积累和收藏,希望可以帮助到您,同时也希望获得您的支持和关注。架构开源地址:https://gitee.com/msxyspringboot整合Ftpserver参...

Linux和Windows下:Python Crypto模块安装方式区别

一、Linux环境下:fromCrypto.SignatureimportPKCS1_v1_5如果导包报错:ImportError:Nomodulenamed'Crypt...

Python 3 加密简介(python des加密解密)

Python3的标准库中是没多少用来解决加密的,不过却有用于处理哈希的库。在这里我们会对其进行一个简单的介绍,但重点会放在两个第三方的软件包:PyCrypto和cryptography上,我...

怎样从零开始编译一个魔兽世界开源服务端Windows

第二章:编译和安装我是艾西,上期我们讲述到编译一个魔兽世界开源服务端环境准备,那么今天跟大家聊聊怎么编译和安装我们直接进入正题(上一章没有看到的小伙伴可以点我主页查看)编译服务端:在D盘新建一个文件夹...

附1-Conda部署安装及基本使用(conda安装教程)

Windows环境安装安装介质下载下载地址:https://www.anaconda.com/products/individual安装Anaconda安装时,选择自定义安装,选择自定义安装路径:配置...

如何配置全世界最小的 MySQL 服务器

配置全世界最小的MySQL服务器——如何在一块IntelEdison为控制板上安装一个MySQL服务器。介绍在我最近的一篇博文中,物联网,消息以及MySQL,我展示了如果Partic...

如何使用Github Action来自动化编译PolarDB-PG数据库

随着PolarDB在国产数据库领域荣膺桂冠并持续获得广泛认可,越来越多的学生和技术爱好者开始关注并涉足这款由阿里巴巴集团倾力打造且性能卓越的关系型云原生数据库。有很多同学想要上手尝试,却卡在了编译数据...

面向NDK开发者的Android 7.0变更(ndk android.mk)

订阅Google官方微信公众号:谷歌开发者。与谷歌一起创造未来!受Android平台其他改进的影响,为了方便加载本机代码,AndroidM和N中的动态链接器对编写整洁且跨平台兼容的本机...

信创改造--人大金仓(Kingbase)数据库安装、备份恢复的问题纪要

问题一:在安装KingbaseES时,安装用户对于安装路径需有“读”、“写”、“执行”的权限。在Linux系统中,需要以非root用户执行安装程序,且该用户要有标准的home目录,您可...

OpenSSH 安全漏洞,修补操作一手掌握

1.漏洞概述近日,国家信息安全漏洞库(CNNVD)收到关于OpenSSH安全漏洞(CNNVD-202407-017、CVE-2024-6387)情况的报送。攻击者可以利用该漏洞在无需认证的情况下,通...

Linux:lsof命令详解(linux lsof命令详解)

介绍欢迎来到这篇博客。在这篇博客中,我们将学习Unix/Linux系统上的lsof命令行工具。命令行工具是您使用CLI(命令行界面)而不是GUI(图形用户界面)运行的程序或工具。lsoflsof代表&...

幻隐说固态第一期:固态硬盘接口类别

前排声明所有信息来源于网络收集,如有错误请评论区指出更正。废话不多说,目前固态硬盘接口按速度由慢到快分有这几类:SATA、mSATA、SATAExpress、PCI-E、m.2、u.2。下面我们来...

新品轰炸 影驰SSD多款产品登Computex

分享泡泡网SSD固态硬盘频道6月6日台北电脑展作为全球第二、亚洲最大的3C/IT产业链专业展,吸引了众多IT厂商和全球各地媒体的热烈关注,全球存储新势力—影驰,也积极参与其中,为广大玩家朋友带来了...