MyBatis动态sql
动态sql中主要有四个标签
- if
- trim
- choose
- foreach
if标签过于简单,这里就不介绍了
trim标签的使用
trim是一个sql语句格式化的标记,可以对sql语句进行完美的拼接
select语句中trim的使用
select * from user
<trim prefix="where" prefixoverride="and | or">
<if test="id!=null">and id=#{id}</if>
</trim>
上述sql语句拼接的结果:假使传入的参数id不为null,那么sql语句为
select * from user where id=#{id}
假使id为null,那么就变成了
select * from user;
在trim标签中,
参数
prefix指的是前缀
prefixoverride表示去除多余的前缀(这里去除的是多余的and|or)
因此在最后的sql语句中不会出现and
update语句中trim的使用
update user
<trim prefix="set" suffixoverride="," suffix="where id=#{id}">
<if test="name!=null and name.length()>0">name=#{name},</if>
<if test="password!=null and password.length()>0">password=#{password},</if>
</trim>
上述sql语句的拼接结果为:假使name和password都满足要求
update user set name=#{name},password=#{password} where id=#{id};
不满足条件时,会sql语句错误,即sql语句拼接成如下所示
update user
参数:
prefix:前缀
suffix:后缀
suffixoverride:去除多余的后缀(这里去除的是多余的逗号)
注意:name.length()这个方法,只有在你的字段为字符串时才能使用
choose标签的使用
choose标签类似于java中的switch语句,多个条件中选择其一。
这是一个简单的模糊查询语句
select * from user where id=#{id}
<choose>
<when test="name!=null and name.length()>0">
and name like concat("%",#{name},"%")
</when>
<when test="title!=null and title.length()>0">
and title like concat("%",#{title},"%")
</when>
</choose>
name参数不为null的时候,则根据name参数进行模糊查找,反之,name参数为null,title参数不为null,那么就根据title进行模糊查找
foreach标签
foreach标签主要用于对一些集合进行遍历
select * from user where id in
<foreach item="list" item="item_id" collection="list"
open="(" separator="," close=")">
#{item_id}
</foreach>
参数解析:
collection:指定要遍历的集合:
list类型的参数会特殊处理封装在map中,map的key就叫list
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。遍历list的时候是index就是索引,item就是当前值
遍历map的时候index表示的就是map的key,item就是map的值
#{变量名}就能取出变量的值也就是当前遍历出的元素