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 intidValues.length;
for (int i = 0; i < idValues.length; i++) {
try {
intArrayi = Integer.parseInt(idValuesi);
} 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语句当中
作⽤:代码复⽤。易维护。
例如

相关推荐
知识分享小能手1 小时前
高等数学学习教程,从入门到精通,定积分 — 知识点全面总结(10)
学习·机器学习·概率论
一米阳光86617 小时前
软考(中级)软件设计师核心笔记(3)数据库系统——概念、数据库设计
数据库·笔记·职场发展·软考·软件设计师
漏刻有时8 小时前
PHP GeoJSON转PNG地图渲染程序开发笔记、源码解读、问题复盘与整改方案
android·笔记·php
暗影凋落8 小时前
CMake构建学习笔记-SQLite库的构建
笔记·学习·sqlite
画面无声9 小时前
STM32的SPI通信原理与练习记录
c语言·stm32·单片机·嵌入式硬件·学习
zzm62810 小时前
精读KDD 2017最佳论文:通过类比挖掘加速创新 | 阅读笔记
笔记
你有哈莫吗10 小时前
CMake构建学习笔记-iconv库的构建
笔记·学习
ctlover11 小时前
Python学习第4日
学习
小弥儿12 小时前
GitHub今日热榜 | 2026-08-01:硬件安全工具与AI教育并行
人工智能·学习·开源·github
秋雨梧桐叶落莳12 小时前
计算器仿写总结
学习·macos·ios·objective-c·cocoa