Mybatis学习笔记9 动态SQL

Mybatis学习笔记8 查询返回专题_biubiubiu0706的博客-CSDN博客

动态SQL的业务场景:

例如

批量删除

get请求 uri?id=18&id=19&id=20 或者post id=18&id=19&id=20

String[] ids=request.getParameterValues("id")

那么这句SQL是需要动态的

还有像如下的多条件查询

可能不提供条件: 0条件 select & from t_product;

当选择了一个或多个条件: select * from t_product where 条件1=#{xxx} and 条件2=#{xxx2}

新建模块

1. if标签

2.where标签 作用让where子句更加动态智能

当所有条件都为空时,where标签保证不会生成where子句

自动去除某些条件前面多余的and和or

3.trim标签

prefix:在trim标签中的语句前添加内容
suffix:在trim标签中的语句后 添加 内容

prefixOverrides:前缀覆盖掉(去掉)
suffixOverrides:后缀 覆盖掉(去掉)

trim会自动判断里面if来考虑是否添加where 并且自动判断是否去掉 and或者or

4.set标签
主要使⽤在update语句当中,⽤来⽣成set关键字,同时去掉最后多余的","



5.choose when otherwise
< choose >
< when ></ when >
< when ></ when >
< when ></ when >
< otherwise ></ otherwise >
</ choose >
一般<choose>会和<when><otherwise>联合使用
等价于
if (){
} else if (){
} else if (){
} else if (){
} else {
}
只有⼀个分⽀会被选择!!!! 只要一个分支执行,条件语句结束 只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!
比如说下面的三个参数都是""或者 null
那么 最后执行
select * from t_car where car_type= "" 或者 select * from t_car where car_type= null

实际使用比如
比如需求是:先根据品牌查,没有提供品牌按价格查,没有提供价格按类型查


这里注意下

6.foreach标签
循环数组或集合,动态⽣成sql
批量删除:
id=1&id=2&id=3
String[] ids=request.getParameterValues("id");
String[] ids={"1","2","3"}
int[] intArray = new int[idValues.length];
for (int i = 0; i < idValues.length; i++) {
try {
intArray[i] = Integer.parseInt(idValues[i]);
} catch (NumberFormatException e) {
}
delete from t_car where id in ( 1 , 2 , 3 );
delete from t_car where id = 1 or id = 2 or id = 3 ;
第一种方式: delete from t_car where id in ( 1 , 2 , 3 );


第二种方式: delete from t_car where id = 1 or id = 2 or id = 3 ;


批量插入
比如 一次插入多条数据
insert into user(id,name,age) values(1,'zs',18),(2,'ls',19),(3,'ww',21)



7 sql标签与include标签
sql标签⽤来声明sql⽚段
include标签⽤来将声明的sql⽚段包含到某个sql语句当中
作⽤:代码复⽤。易维护。
例如

相关推荐
Aision_2 小时前
从工具调用到 MCP、Skill完整学习记录
java·python·gpt·学习·langchain·prompt·agi
剑飞的编程思维2 小时前
真实学习本质-坚持思考的人
学习
AI浩2 小时前
学习嵌入位置:面向小目标检测查询检索的噪声感知位置编码
人工智能·学习·目标检测
辞旧 lekkk6 小时前
【Qt】信号和槽
linux·开发语言·数据库·qt·学习·mysql·萌新
爱上好庆祝9 小时前
学习js的第七天(wed APIs的开始)
前端·javascript·css·学习·html·css3
问心无愧05139 小时前
ctf show web入门37
笔记
羊群智妍10 小时前
2026生成式AI搜索优化:GEO监测工具全解析
笔记
哆啦A梦158811 小时前
20, Springboot3+vue3实现前台轮播图和详情页的设计
javascript·数据库·spring boot·mybatis·vue3
风兮雨露11 小时前
VMware虚拟机(安装/绿色版)
学习
koo36411 小时前
周报5.10
笔记