常用标签
- if
- choose (when, otherwise)
- foreach
- where
if
if标签和java中的作用一样
<if test="username!=null and username!=''">
</if>
上述代码块中的if标签即判断username是否为null和空字符串
当需要判断条件同时成立时需要用and关键字而不能使用&&
where
where标签用来代替 sql语句中的where关键字
当sql拼接时需要用if判断 where关键字后面的条件
除第一个条件外都有and关键字
SELECT * FROM tb_user
where
<if test="username!=null and username!=''">
id>5
</if>
<if test="gender!=null and gender!=''">
and gender='男'
</if>
<if test="addr!=null and addr!=''">
and addr='武夷'
</if>
如果不使用where标签 且第一个if判断不成立时,
则会变成:
where and gender='男' and addr='武夷'
明显语法错误 where标签会解决这样的问题
foreach
当需要根据多个id删除数据时 可以把id封装成一个数组或集合传入
foreach标签可以用来遍历数组
delete from tb_brand where id in
<foreach collection="array" separator="," item="id" open="(" close=")">
#{id}
</foreach>
其中的属性分别是
collection代表传入参数的类型 array 即为数组
separator表示传入的参数以什么分割
item代表遍历时的临时变量 需要与下方#{}中的变量名保持一致
open代表delete from tb_brand where id in 后拼接的第一个字符串
close则代表最后一个字符串
choose (when, otherwise)
choose的功能与java中的switch类似
使用场景
当需要选择列名 再根据列名进行模糊查询时
select *
from tb_brand
<where>
<choose><!--相当于switch-->
<when test="status != null"><!--相当于case-->
status = #{status}
</when>
<when test="companyName != null and companyName != '' "><!--相当于case-->
company_name like #{companyName}
</when>
<when test="brandName != null and brandName != ''"><!--相当于case-->
brand_name like #{brandName}
</when>
</choose>
</where>