MyBatis动态SQL

81 阅读2分钟

一、where+if:

自动判断其内部是否有返回值,如果有,则插入一个where并自动删除SQL语句前多余的and或or

select * from smbms_user userName like concat('%',#{name},'%') and userRole=#{role}

二、set+if:

t标签自动判断其内部是否有返回值,如果有则插入一个set,并且删除SQL语句最后一个逗号

update smbms_user

userCode=#{userCode},

userPassword=# {userPassword},

userName=#{userName},

gender=#{gender},

birthday=#{birthday},

phone=#{phone},

address=#{address},

userRole=#{userRole},

createdBy=#{createdBy},

creationDate=#{creationDate},

modifyBy=#{modifyBy},

modifyDate=#{modifyDate},

where id=#{id}

三、foreach:

自动遍历参数数组或今后。

属性:

  • collection:参数(Map集合)的键名,如果是数组,键名自动为array;如果是List,键名自动是list;如果是Map,键名需要于定义的键名保持相同。
  • item:参数名
  • oppen/close:以oppen开始,close结束
  • separator:一般是逗号
select * from smbms_user where userRole in #{roles}

四、MyBatis参数小结:

1、MyBatis可以接收的参数类型有:基本数据类型、对象、List、数组、Map

2、无论是哪种类型,MyBatis都会将它封装一个Map集合

3、如果是单个参数有一下几种情况:

  • 参数是基本数据类型:变量名为key,变量值为value;
  • 参数是对象:对象的属性名为key,属性值为value;
  • 参数是List:默认将“list”为key,该List本身为value;
  • 参数数数组:默认将“array”为key,该数组本身为value;
  • 参数是Map:MyBatis就使用我们自定义的键值对

五、choose+when+otherwise:

类似于Java中的switch结构,和JSTL中的choose基本一样;

以此判断中的语句是否有返回值,如果有,则执行,并跳出整个结构;如果没有,则默认执行中的语 句,并且可省略

六、分页:

limit x,y: x从哪一行开始显示(下标从0开始),y显示y条

(m-1)*n

七、trim+if:

自动判断内部是否有返回值,如果有,则插入一个“前缀”或“后缀”,并且自动覆盖SQL语句中的指定内容:“前缀覆盖”“后缀覆盖”。

prefix:前缀 suffix:后缀

prefixOverrides:前缀覆盖

select * from smbms_user userName like concat('%',#{name},'%') and userRole=#{role}

生成的SQL语句:select * from smbms_user where userName like concat('%',?,'%')

seffixOverrides:后缀覆盖

update smbms_user

userCode=#{userCode},

userPassword=#{userPassword},

userName=#{userName},

gender=#{gender},

birthday=#{birthday},

phone=#{phone},

address=#{address},

userRole=#{userRole},

createdBy=#{createdBy},

creationDate=#{creationDate},

modifyBy=#{modifyBy},

modifyDate=#{modifyDate},

生成的SQL语句:update smbms_user set userPassword=?, userName=? where id=?