用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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐