【mybatis】mybatis中避免where空条件后面添加1=1垃圾条件的 优化方法 <where>标签

在mybatis中拼接查询语句,偶尔会出现where后面可能一个字段的值都没有,就导致所有条件无效,导致where没有存在的意义;但也有可能这些条件会存在。那解决这个问题的方法,最常见的就是:

在where后面添加1=1

<select id="findActiveBlogLike" resultType="Blog">
 SELECT * FROM BLOG
 WHERE 1=1
 <if test="state != null">
 and state = #{state}
 </if> 
</select>

 

但是这种做法有一个最大的弊端,就是导致数据表上的索引失效,如果有索引的话。而且还是一个垃圾条件

 

所以正确的做法应该是:

使用<where>标签 解决这个问题

where标签会自动处理第一个为null时候的and问题

<select
            id="findUiImage4Map"
            parameterType="com.pisen.cloud.luna.ms.ten.ui.config.base.domain.UiImage"
            resultType="java.util.HashMap">

        select
          uid,
          imgUrl
        from
        ui_image uii
        <where>
            <if test="imgType != null and imgType != '' ">
                AND
                uii.img_type = #{imgType}
            </if>

            <if test="uploadDate != null and uploadDate != '' ">
                AND
                DATE_FORMAT(uii.upload_date,'%Y-%m-%d') = DATE_FORMAT(#{uploadDate},'%Y-%m-%d')
            </if>

        </where>

    </select>

 

posted @ 2018-08-03 09:50  Angel挤一挤  阅读(2921)  评论(0编辑  收藏  举报