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 {
}
只有⼀个分⽀会被选择!!!! 只要一个分支执行,条件语句结束 只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!只有⼀个分⽀会被选择,且必会选择!!!!
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语句当中
作⽤:代码复⽤。易维护。
例如
