XML动态sql的常用标签及用法

常用标签

  • 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值