用where和if进行组合,当条件不成立时,if条件后的内容包括and会存在,因此会对整个sql语句产生影响
写法一:
每个if判断前添加and时,在if前添加1 = 1

    <select id="select" resultType="com.tzh.bean.Entity">
        select * from department
        where 1=1
            <if test="id!=null">
                and id=#{id}
            </if>
            <if test="name!=null and name!=''">
                and t_name like #{name}
            </if>
            <if test="email!=null and email.trim()!=''">
                and email=#{email}
            </if> 
     </select>

写法一:
每个if判断后添加and时,在if判断后添加1 = 1

    <select id="select" resultType="com.tzh.bean.Entity">
        select * from department
        where 
            <if test="id!=null">
                 id=#{id} and
            </if>
            <if test="name!=null and name!=''">
                t_name like #{name}  and
            </if>
            <if test="email!=null and email.trim()!=''">
                email=#{email}  and
            </if> 
            1=1
     </select>

建议方式:
使用转义符

    <select id="select" resultType="com.tzh.bean.Entity">
        select * from department
        where 
     <if test="id!=null">
            id=#{id}
        </if>
        <if test="name!=null &amp;&amp; name!=&quot;&quot;">
            and t_name like #{name}
        </if>
        <if test="email!=null and email.trim()!=&quot;&quot;">
            and email=#{email}
        </if> 
    </where>

附上转义符表
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐