12. Mybatis 多表查询 动态 SQL
目录
1. 数据库字段和 Java 对象不一致
2. 多表查询
3. 动态 SQL 使用
4. if 标签
5. trim 标签
6. where 标签
7. set 标签
8. foreach 标签
9. 通过注解实现
9.1 查找所有数据
9.2 通过 id 查找
1. 数据库字段和 Java 对象不一致
我们先来看一下数据库中的数据:

接下来,我们在之前代码的基础上修改字段的名称:
/*** 数据库字段和 Java 对象不完全一致*/
@Data
public class User {private Integer id;private String name;private String pwd;private String photo;private Date createtime;private Date updatetime;
}
@Slf4j
@SpringBootTest
class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testvoid queryAll() {List<User> users = userMapper.queryAll();log.info(users.toString());}@BeforeEachvoid setUp() {log.info("before...");}@AfterEachvoid tearDown() {log.info("after...");}
}
可以看到能够获取数据,但是对应字段的值为 null 了:

因为数据库的字段命名规则和 Java 的命名规则不一致,数据库命名:字母小写,以下划线分割;Java 属性命名:小驼峰,第一个英文单词首字母小写,其他英文单词首字母大写。
一个 xml 文件中,可以存在多个 resultMap,只需要 id 不同即可:

List<User> queryAllMap();
<resultMap id="BaseMap" type="com.example.demo.model.User"><id property="id" column="id"></id><result property="name" column="username"></result><result property="pwd" column="password"></result></resultMap><select id="queryAllMap" resultMap="BaseMap">select * from userinfo</select>
@Testvoid queryAllMap() {List<User> users = userMapper.queryAllMap();log.info(users.toString());}
此时,我们可以看到成功查询到数据:

那么具体的关系如下图标注所示:

2. 多表查询
我们再新建一张表:
-- 创建⽂章表
drop table if exists articleinfo;
create table articleinfo(id int primary key auto_increment,title varchar(100) not null,content text not null,createtime datetime default now(),updatetime datetime default now(),uid int not null,rcount int not null default 1,`state` int default 1
)default charset 'utf8mb4';
如下图所示:

添加文章的数据:
-- ⽂章添加测试数据
insert into articleinfo(title,content,uid)values('Java','Java正⽂',1);
文章添加数据后,如下图所示:

首先是 SQL 语句的多表查询:
select * from articleinfo ta
left join userinfo tb on ta.uid = tb.id;

接下来通过 Mybatis 实现:
首先新建 ArticleInfo 类:
@Data
public class ArticleInfo {private Integer id;private String title;private String content;private Date createtime;private Date updatetime;private Integer rcount;private User user;
}
新建 ArticleMapper.xml 文件:
<resultMap id="BaseMap" type="com.example.demo.model.ArticleInfo"><id property="id" column="id"></id><result property="title" column="title"></result><result property="content" column="content"></result><result property="createtime" column="createtime"></result><result property="updatetime" column="updatetime"></result><association property="user" resultMap="com.example.demo.mapper.UserMapper.BaseMap"></association></resultMap><select id="queryArticle" resultMap="BaseMap">select *from articleinfo taleft join userinfo tb on ta.uid = tb.id</select>
添加测试类:
@Slf4j
@SpringBootTest
class ArticleMapperTest {@Autowiredprivate ArticleMapper articleMapper;@Testvoid queryArticle() {List<ArticleInfo> articleInfos = articleMapper.queryArticle();log.info(articleInfos.toString());}
}
运行结果如下图所示:

我们可以看到上述方式的结果显示的不够完整且需要输入的 SQL 语句过多。
接下来,我们通过另一种方式来实现:
List<ArticleInfo> queryArticle2();
在 ArticleMapper.xml 文件中添加以下配置:
<resultMap id="BaseMap2" type="com.example.demo.model.ArticleInfo"><id property="id" column="id"></id><result property="title" column="title"></result><result property="content" column="content"></result><result property="createtime" column="createtime"></result><result property="updatetime" column="updatetime"></result><result property="userId" column="userid"></result><result property="username" column="username"></result></resultMap><select id="queryArticle2" resultMap="BaseMap2">selectta.*,tb.id as userid,tb.username as usernamefrom articleinfo taleft join userinfo tb on ta.uid = tb.id</select>
添加测试类:
@Testvoid queryArticle2() {List<ArticleInfo> articleInfos = articleMapper.queryArticle2();log.info(articleInfos.toString());}
查询数据如下图所示:

需要注意,在实际的开发中,要尽量避免使用 *,无论数据库中有多少字段都需要一一罗列出来。
如下所示:
<resultMap id="BaseMap2" type="com.example.demo.model.ArticleInfo"><id property="id" column="id"></id><result property="title" column="title"></result><result property="content" column="content"></result><result property="createtime" column="createtime"></result><result property="updatetime" column="updatetime"></result><result property="userId" column="userid"></result><result property="username" column="username"></result></resultMap><select id="queryArticle2" resultMap="BaseMap2">selectta.id as id,ta.title as title,ta.content as content,ta.createtime as createtime,ta.updatetime as updatetime,tb.id as userid,tb.username as usernamefrom articleinfo taleft join userinfo tb on ta.uid = tb.id</select>
3. 动态 SQL 使用
在实际的应用中,并不是每个信息都是必填的,也就是动态 SQL根据输入参数的不同动态的拼接 SQL。
我们先来看一下表中现有的数据:

接下来,我们插入数据:
void insert(ArticleInfo articleInfo);
<insert id="insert">insert into articleinfo(title,content,uid,state)values (#{title},#{content},#{userId},#{state})</insert>
@Testvoid insert() {ArticleInfo articleInfo = new ArticleInfo();articleInfo.setTitle("测试文章");articleInfo.setContent("测试文章内容");articleInfo.setUserId(1);articleInfo.setState(null);articleMapper.insert(articleInfo);}


可以看到,上面我们是自行将 state 的值设置为了 null,那么如果我们没有给这个字段赋值呢?
修改 XML 文件:
<insert id="insert">insert into articleinfo(title,content,uid)values (#{title},#{content},#{userId})</insert>

可以看到当我们没有对 state 赋值时,进行了自动默认赋值为1:
那么,这显然是不符合我们的预期的,我们想要实现的是当用户没有输入数据时,应该为默认值;输入数据时,显示为输入的数据。此时就需要用到标签了。
4. <if> 标签
我们的目标是根据用户输入的情况,动态拼接 SQL。
void insertByCondition(ArticleInfo articleInfo);
<insert id="insertByCondition">insert into articleinfo(title,content,uid<if test="state!=null">,state</if>)values(#{title},#{content},#{userId}<if test="state!=null">,#{state}</if>)</insert>
@Testvoid insertByCondition() {ArticleInfo articleInfo = new ArticleInfo();articleInfo.setTitle("测试文章2");articleInfo.setContent("测试文章内容2");articleInfo.setUserId(1);articleMapper.insert(articleInfo);}

由于我们并没有设置 state 的状态,因此默认为1:
接下来我们设置 state 为0:
@Testvoid insertByCondition() {ArticleInfo articleInfo = new ArticleInfo();articleInfo.setTitle("测试文章3");articleInfo.setContent("测试文章内容3");articleInfo.setUserId(1);articleInfo.setState(0);articleMapper.insertByCondition(articleInfo);}
可以看到成功运行:


当我们需要对多个字段应用 if 标签时,会存在报错:

如果统一把逗号放在字段前面,当第一个字段为 null 时,整个 SQL 的最前面就会多一个逗号;如果统一把逗号放在字段后面,当最后一个字段为 null 时,整个 SQL 的最后面会多一个逗号。
5. <trim> 标签
上面的插入数据功能,如果所有字段都是非必填项,就考虑使用标签结合标签,对多个字段都采取动态生成的方式。 标签中有如下属性:
- prefix:表示整个语句块,以prefix的值作为前缀
- suffix:表示整个语句块,以suffix的值作为后缀
- prefixOverrides:表示整个语句块要去除掉的前缀
- suffixOverrides:表示整个语句块要去除掉的后缀
使用 <trim> 标签:
<insert id="insertByCondition">insert into articleinfo<trim prefix="(" suffix=")" prefixOverrides="," suffixOverrides=","><if test="title!=null">title,</if><if test="content!=null">content,</if><if test="userId!=null">uid,</if><if test="state!=null">state</if></trim>values<trim prefix="(" suffix=")" prefixOverrides="," suffixOverrides=","><if test="title!=null">#{title},</if><if test="content!=null">#{content},</if><if test="userId!=null">#{content},</if><if test="state!=null">#{state},</if></trim></insert>
可以看到此时能够正确执行:

6. <where> 标签
当我们需要使用 where 语句进行条件筛选时:
List<ArticleInfo> queryBycondition(@Param("uid") Integer uid,@Param("state")Integer state);
<select id="queryBycondition" resultType="com.example.demo.model.ArticleInfo">select * from articleinfowhere<if test="uid!=null">uid = #{uid}</if><if test="state!=null">and state=#{state}</if></select>
@Testvoid queryBycondition() {List<ArticleInfo> articleInfos = articleMapper.queryBycondition(1,1);log.info(articleInfos.toString());}
可以看到成功执行:

此时我们修改代码如下:
@Testvoid queryBycondition() {List<ArticleInfo> articleInfos = articleMapper.queryBycondition(1,null);log.info(articleInfos.toString());}
依然可以成功执行:

当我们修改代码如下时:
@Testvoid queryBycondition() {List<ArticleInfo> articleInfos = articleMapper.queryBycondition(null,1);log.info(articleInfos.toString());}
产生报错信息:

添加语句 1 = 1,继续修改代码如下:
<select id="queryBycondition" resultType="com.example.demo.model.ArticleInfo">select * from articleinfowhere 1 = 1<if test="uid!=null">and uid = #{uid}</if><if test="state!=null">and state=#{state}</if></select>
此时可以看到成功执行:

接下来,我们使用 where 标签实现以上功能。
在 XML 文件中,添加以下语句:
<select id="queryBycondition" resultType="com.example.demo.model.ArticleInfo">select * from articleinfo<where><if test="uid!=null">and uid = #{uid}</if><if test="state!=null">and state=#{state}</if></where></select>
可以已经生成了 where 并且去掉了 and :

当两个字段均为 null 时,可以看到直接去掉了 where:
@Testvoid queryBycondition() {List<ArticleInfo> articleInfos = articleMapper.queryBycondition(null,null);log.info(articleInfos.toString());}

综上,我们可以知道 where 标签具有以下作用:
- 生成 where 关键字
- 去除多余的 and
- 如果没有 where 条件,就不会生成 where 关键字
7. <set> 标签
void updateByCondition(@Param("uid") Integer uid,@Param("state")Integer state);
<update id="updateByCondition">update articleinfoset<if test="uid!=null">uid = #{uid},</if><if test="state!=null">state = #{state},</if></update>
@Testvoid updateByCondition() {articleMapper.updateByCondition(1,null);}
运行后,产生以下报错:

接下来,我们使用 set 标签:
<update id="updateByCondition">update articleinfo<set><if test="uid!=null">uid = #{uid},</if><if test="state!=null">state = #{state},</if></set></update>
运行成功:

综上,我们可以看到 set 标签的作用:
- 生成 set 关键字
- 去除最后一个逗号(也可以使用 trim 标签)
8. <foreach> 标签
对集合进行遍历时可以使用该标签。标签有如下属性:
- collection:绑定方法参数中的集合,如 List,Set,Map或数组对象
- item:遍历时的每⼀个对象
- open:语句块开头的字符串
- close:语句块结束的字符串
- separator:每次遍历之间间隔的字符串
因此,我们来通过 foreach 标签实现以下目标:


接下来我们通过代码实现:
void batchDelete(List<Integer> ids);
<delete id="batchDelete">delete from articleinfo where id in<foreach collection="list" open="(" close=")" separator="," item="id">#{id}</foreach></delete>
@Testvoid batchDelete() {List<Integer> ids = Arrays.asList(2,3,4,5,6,10,11);articleMapper.batchDelete(ids);}
可以看到成功运行:

表中相应的数据也删除了:

注意:

还需要注意的是 collection 也可以是参数的名称:


9. 通过注解实现
Mybatis 的实现有两种方式:
- xml
- 注解
9.1 查找所有数据
接下来,我们来看一下如何通过注解来实现:
@Mapper
public interface UserMapper2 {@Select("select * from userinfo")List<User> queryAll();
}
@Slf4j
@SpringBootTest
class UserMapper2Test {@Autowiredprivate UserMapper2 userMapper2;@Testvoid queryAll() {List<User> userList = userMapper2.queryAll();log.info(userList.toString());}
}
运行结果如下:

9.2 通过 id 查找
@Mapper
public interface UserMapper2 {@Select("select * from userinfo where id = #{uid}")User queryById(Integer aaa);
}
@Slf4j
@SpringBootTest
class UserMapper2Test {@Autowiredprivate UserMapper2 userMapper2;@Testvoid queryById() {User user = userMapper2.queryById(1);log.info(user.toString());}
}
可以看到运行结果如下:

一个项目中,注解和 XML 的方式可以并存,对于简单的 SQL 使用注更加方便,但是对于动态 SQL 注解写起来非常麻烦。

相关文章:
12. Mybatis 多表查询 动态 SQL
目录 1. 数据库字段和 Java 对象不一致 2. 多表查询 3. 动态 SQL 使用 4. if 标签 5. trim 标签 6. where 标签 7. set 标签 8. foreach 标签 9. 通过注解实现 9.1 查找所有数据 9.2 通过 id 查找 1. 数据库字段和 Java 对象不一致 我们先来看一下数据库中的数…...
操作系统专栏1-内存管理from 小林coding
操作系统专栏1-内存管理 虚拟地址内存管理方案分段分页页表单级页表多级页表TLB 段页式内存管理Linux内存管理 malloc工作方式操作系统内存回收回收的内存种类 预读失败和缓存污染问题预读机制预读机制失效解决方案缓存污染 内核对虚拟内存的表示内核对内核空间的表示直接映射区…...
SpringCloud远程服务调用
下面介绍在SpringCloud中如何使用openfeign实现远程服务调用 1.在字典服务中有这么2个接口 Api(tags "数据字典接口") RestController RequestMapping("/admin/cmn/dict/") CrossOrigin public class DictController {Autowiredprivate DictService dic…...
Arcgis通过模型构建器计算几何坐标
模型 模型中,先添加字段,再计算字段 计算字段 模型的计算字段中,表达式是类似这样写的,其中Xmin表示X坐标,Ymin表示Y坐标 !Shape.extent.Xmin!...
java设计模式-工厂模式(下)
接java设计模式-工厂模式(上) 抽象工厂模式 针对耳机的生产需求,我们可以知道,刚才的工厂已经不满足了,因为只是生产一类产品-手机,但是现在我们需要的工厂类是要生产一个产品族(手机和耳机&a…...
深蓝学院C++基础与深度解析笔记 第13章 模板
1. 函数模板 ● 使用 template 关键字引入模板: template<typename T> //声明:T模板形参void fun(T); // T 函数形参template<typename T> //定义void fun(T) {...}– 函数模板不是函数 –…...
装饰器模式——扩展系统功能
1、简介 1.1、概述 对新房进行装修并没有改变房屋用于居住的本质,但它可以让房子变得更漂亮、更温馨、更实用、更能满足居家的需求。在软件设计中,也有一种类似新房装修的技术可以对已有对象(新房)的功能进行扩展(装…...
无涯教程-jQuery - jQuery.get( url, data, callback, type )方法函数
jQuery.get(url,[data],[callback],[type])方法使用GET HTTP请求从服务器加载数据。 该方法返回XMLHttpRequest对象。 jQuery.get( url, [data], [callback], [type] ) - 语法 $.get( url, [data], [callback], [type] ) 这是此方法使用的…...
【Vue3】递归组件
1. 递归组件mock数据 App.vue <template><div><Tree :data"data"></Tree></div> </template><script setup lang"ts"> import { reactive } from vue; import Tree from ./components/Tree.vue; interface Tr…...
【Python】数据分析+数据挖掘——探索Pandas中的索引与数据组织
前言 在数据科学和数据分析领域,Pandas是一个备受喜爱的Python库。它提供了丰富的数据结构和灵活的工具,帮助我们高效地处理和分析数据。其中,索引在Pandas中扮演着关键角色,它是一种强大的数据组织和访问机制,使我们…...
matlab进阶:求解在约束条件下的多元目标函数最值(fmincon函数详解)
🌅*🔹** φ(゜▽゜*)♪ **🔹*🌅 欢迎来到馒头侠的博客,该类目主要讲数学建模的知识,大家一起学习,联系最后的横幅! 喜欢的朋友可以关注下,私信下次更新不迷路࿰…...
Kotlin知识点
Kotlin 是 Google 推荐的用于创建新 Android 应用的语言。使用 Kotlin,可以花更短的时间编写出更好的 Android 应用。 基础 Kotlin 程序必须具有主函数,这是 Kotlin 编译器在代码中开始编译的特定位置。主函数是程序的入口点,或者说是起点。…...
亚马逊云科技联合霞光社发布《2013~2023中国企业全球化发展报告》
中国企业正处于全球聚光灯下。当企业全球化成为时代发展下的必然趋势,出海也从“可选项”变为“必选项”。中国急速扩大的经济规模,不断升级的研发和制造能力,都在推动中国企业不断拓宽在全球各行业的疆域。 过去十年,是中国企业…...
【解析excel】利用easyexcel解析excel
【解析excel】利用easyexcel解析excel POM监听类工具类测试类部分测试结果备注其他 EasyExcel Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题&…...
JQuery操作单选按钮Radio和复选框checkbox
获取选中值: $(input:radio:checked).val();$("input[typeradio]:checked").val();$("input[namerd]:checked").val();$("input[idrand_question]:checked").val();设置第一个Radio为选中值: $(input:radio:…...
7.28 作业 QT
手动完成服务器的实现,并具体程序要注释清楚: widget.h: #ifndef WIDGET_H #define WIDGET_H#include <QWidget> #include <QTcpServer> //服务器类 #include <QTcpSocket> //客户端类 #include <QMessageBox> //对话框类 #include …...
HTML <pre> 标签
定义和用法 pre 元素可定义预格式化的文本。被包围在 pre 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。 <pre> 标签的一个常见应用就是用来表示计算机的源代码。 可以导致段落断开的标签(例如标题、"><p> 和 标签"><a…...
查询结果元数据-MetaData对象、数据库工具类的封装、通过反射实现数据查询的封装
六、查询结果元数据-MetaData对象 七、数据库工具类的封装 1、PropertieUtil类 2、DbUtil类 3、DBHepler类 查询: 4、TestDb测试类: 更新: 1)插入: 2)修改: 3)删除: 查…...
【Minio中间件】上传图片并Vue回显
流程: 目录 1.文件服务器Minio的安装 1.1 下载Minio安装后,新建1个data文件夹。并在该安装目录cmd 敲命令。注意不要进错目录。依次输入 1.2 登录Minio网页端 1.3 先建1个桶(buckets),点击create a bucket 2. Spr…...
Jmeter配置不同业务请求比例,应对综合场景压测
需求: 每次向服务器发出请求时,先生成一个随机数,我们对随机数的取值划分若干个范围(对应若干个业务请求),然后对随机数进行判断,当随机数落在某个范围内,就可以执行对应的请求。比…...
JavaSec-RCE
简介 RCE(Remote Code Execution),可以分为:命令注入(Command Injection)、代码注入(Code Injection) 代码注入 1.漏洞场景:Groovy代码注入 Groovy是一种基于JVM的动态语言,语法简洁,支持闭包、动态类型和Java互操作性,…...
Flask RESTful 示例
目录 1. 环境准备2. 安装依赖3. 修改main.py4. 运行应用5. API使用示例获取所有任务获取单个任务创建新任务更新任务删除任务 中文乱码问题: 下面创建一个简单的Flask RESTful API示例。首先,我们需要创建环境,安装必要的依赖,然后…...
QMC5883L的驱动
简介 本篇文章的代码已经上传到了github上面,开源代码 作为一个电子罗盘模块,我们可以通过I2C从中获取偏航角yaw,相对于六轴陀螺仪的yaw,qmc5883l几乎不会零飘并且成本较低。 参考资料 QMC5883L磁场传感器驱动 QMC5883L磁力计…...
Objective-C常用命名规范总结
【OC】常用命名规范总结 文章目录 【OC】常用命名规范总结1.类名(Class Name)2.协议名(Protocol Name)3.方法名(Method Name)4.属性名(Property Name)5.局部变量/实例变量(Local / Instance Variables&…...
linux 错误码总结
1,错误码的概念与作用 在Linux系统中,错误码是系统调用或库函数在执行失败时返回的特定数值,用于指示具体的错误类型。这些错误码通过全局变量errno来存储和传递,errno由操作系统维护,保存最近一次发生的错误信息。值得注意的是,errno的值在每次系统调用或函数调用失败时…...
NFT模式:数字资产确权与链游经济系统构建
NFT模式:数字资产确权与链游经济系统构建 ——从技术架构到可持续生态的范式革命 一、确权技术革新:构建可信数字资产基石 1. 区块链底层架构的进化 跨链互操作协议:基于LayerZero协议实现以太坊、Solana等公链资产互通,通过零知…...
多种风格导航菜单 HTML 实现(附源码)
下面我将为您展示 6 种不同风格的导航菜单实现,每种都包含完整 HTML、CSS 和 JavaScript 代码。 1. 简约水平导航栏 <!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport&qu…...
基于SpringBoot在线拍卖系统的设计和实现
摘 要 随着社会的发展,社会的各行各业都在利用信息化时代的优势。计算机的优势和普及使得各种信息系统的开发成为必需。 在线拍卖系统,主要的模块包括管理员;首页、个人中心、用户管理、商品类型管理、拍卖商品管理、历史竞拍管理、竞拍订单…...
现有的 Redis 分布式锁库(如 Redisson)提供了哪些便利?
现有的 Redis 分布式锁库(如 Redisson)相比于开发者自己基于 Redis 命令(如 SETNX, EXPIRE, DEL)手动实现分布式锁,提供了巨大的便利性和健壮性。主要体现在以下几个方面: 原子性保证 (Atomicity)ÿ…...
【Nginx】使用 Nginx+Lua 实现基于 IP 的访问频率限制
使用 NginxLua 实现基于 IP 的访问频率限制 在高并发场景下,限制某个 IP 的访问频率是非常重要的,可以有效防止恶意攻击或错误配置导致的服务宕机。以下是一个详细的实现方案,使用 Nginx 和 Lua 脚本结合 Redis 来实现基于 IP 的访问频率限制…...
