关于动态sql使用了if标签后导致and拼接出错的解决方法

问题代码:


 <select id="list" resultType="全类名">
        select * from emp
        where
        <if test="name != null">
            name like concat('%',#{name},'%')
        </if>
        <if test="gender != null">
            and gender = #{gender}
        </if>
        <if test="begin != null and end != null">
            and entrydate between #{begin} and #{end}
        </if>

        order by update_time desc
    </select>

说明问题:该SQL语句可以用来动态判断三个条件,

    1、当第一个条件不为空时,可以正常执行。

    2、当第一个条件为空时,会出错
    即:select * from emp where and gender = 1 and entrydate between 1998-02-03 and 2020-02-06 order by update_time desc;  黄色字体出现问题,sql语法出现问题

解决问题:

    1、利用if标签在开始拼接一个结果为真的字符串,且判断条件和之前第一个条件正好相反,具体如下:

     <if test="name == null">
            '1'=1
        </if>

        通过拼接来设定一定存在一个语句,从而避免出现and的错误以及若没有条件只剩下where的问题。

最终语句如下:

 <select id="list" resultType="全类名">
        select * from emp
        where
    <if test="name == null">
            '1'=1
        </if>
        <if test="name != null">
            name like concat('%',#{name},'%')
        </if>
        <if test="gender != null">
            and gender = #{gender}
        </if>
        <if test="begin != null and end != null">
            and entrydate between #{begin} and #{end}
        </if>

        order by update_time desc
    </select>


    2、利用where标签 (方便又快捷)——自动处理相关问题

 <select id="list" resultType="全类名">
        select * from emp
        <where>
            <if test="name != null">
                name like concat('%',#{name},'%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entrydate between #{begin} and #{end}
            </if>
        </where>
        order by update_time desc
    </select>

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值