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

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

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

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

相关推荐

得物可观测平台架构升级:基于GreptimeDB的全新监控体系实践

一、摘要在前端可观测分析场景中,需要实时观测并处理多地、多环境的运行情况,以保障Web应用和移动端的可用性与性能。传统方案往往依赖代理Agent→消息队列→流计算引擎→OLAP存储...

warm-flow新春版:网关直连和流程图重构

本期主要解决了网关直连和流程图重构,可以自此之后可支持各种复杂的网关混合、多网关直连使用。-新增Ruoyi-Vue-Plus优秀开源集成案例更新日志[feat]导入、导出和保存等新增json格式支持...

扣子空间体验报告

在数字化时代,智能工具的应用正不断拓展到我们工作和生活的各个角落。从任务规划到项目执行,再到任务管理,作者深入探讨了这款工具在不同场景下的表现和潜力。通过具体的应用实例,文章展示了扣子空间如何帮助用户...

spider-flow:开源的可视化方式定义爬虫方案

spider-flow简介spider-flow是一个爬虫平台,以可视化推拽方式定义爬取流程,无需代码即可实现一个爬虫服务。spider-flow特性支持css选择器、正则提取支持JSON/XML格式...

solon-flow 你好世界!

solon-flow是一个基础级的流处理引擎(可用于业务规则、决策处理、计算编排、流程审批等......)。提供有“开放式”驱动定制支持,像jdbc有mysql或pgsql等驱动,可...

新一代开源爬虫平台:SpiderFlow

SpiderFlow:新一代爬虫平台,以图形化方式定义爬虫流程,不写代码即可完成爬虫。-精选真开源,释放新价值。概览Spider-Flow是一个开源的、面向所有用户的Web端爬虫构建平台,它使用Ja...

通过 SQL 训练机器学习模型的引擎

关注薪资待遇的同学应该知道,机器学习相关的岗位工资普遍偏高啊。同时随着各种通用机器学习框架的出现,机器学习的门槛也在逐渐降低,训练一个简单的机器学习模型变得不那么难。但是不得不承认对于一些数据相关的工...

鼠须管输入法rime for Mac

鼠须管输入法forMac是一款十分新颖的跨平台输入法软件,全名是中州韵输入法引擎,鼠须管输入法mac版不仅仅是一个输入法,而是一个输入法算法框架。Rime的基础架构十分精良,一套算法支持了拼音、...

Go语言 1.20 版本正式发布:新版详细介绍

Go1.20简介最新的Go版本1.20在Go1.19发布六个月后发布。它的大部分更改都在工具链、运行时和库的实现中。一如既往,该版本保持了Go1的兼容性承诺。我们期望几乎所...

iOS 10平台SpriteKit新特性之Tile Maps(上)

简介苹果公司在WWDC2016大会上向人们展示了一大批新的好东西。其中之一就是SpriteKitTileEditor。这款工具易于上手,而且看起来速度特别快。在本教程中,你将了解关于TileE...

程序员简历例句—范例Java、Python、C++模板

个人简介通用简介:有良好的代码风格,通过添加注释提高代码可读性,注重代码质量,研读过XXX,XXX等多个开源项目源码从而学习增强代码的健壮性与扩展性。具备良好的代码编程习惯及文档编写能力,参与多个高...

Telerik UI for iOS Q3 2015正式发布

近日,TelerikUIforiOS正式发布了Q32015。新版本新增对XCode7、Swift2.0和iOS9的支持,同时还新增了对数轴、不连续的日期时间轴等;改进TKDataPoin...

ios使用ijkplayer+nginx进行视频直播

上两节,我们讲到使用nginx和ngixn的rtmp模块搭建直播的服务器,接着我们讲解了在Android使用ijkplayer来作为我们的视频直播播放器,整个过程中,需要注意的就是ijlplayer编...

IOS技术分享|iOS快速生成开发文档(一)

前言对于开发人员而言,文档的作用不言而喻。文档不仅可以提高软件开发效率,还能便于以后的软件开发、使用和维护。本文主要讲述Objective-C快速生成开发文档工具appledoc。简介apple...

macOS下配置VS Code C++开发环境

本文介绍在苹果macOS操作系统下,配置VisualStudioCode的C/C++开发环境的过程,本环境使用Clang/LLVM编译器和调试器。一、前置条件本文默认前置条件是,您的开发设备已...