mybatis应用(性能调优)1

1:批量删除以及性能调优:(.xml文件)

    <delete id="deleteObjects">
       delete from sys_Logs
       where id in 
       <foreach collection="ids"
                open="("
                close=")"
                separator=","
                item="id">
               #{id} 
        </foreach>
    </delete>

分析:如上SQL实现可能会存在什么问题?(可靠性问题,性能问题)

从可靠性的角度分析,假如ids的值为null或长度为0时,SQL构建可能会出现语法问题,可参考如下代码进行改进(先对ids的值进行判定):

<delete id="deleteObjects">
        delete from sys_logs
        <if test="ids!=null and ids.length>0">
          where id in  
            <foreach collection="ids"
                 open="("
                 close=")"
                 separator=","
                 item="id">
                 #{id}
            </foreach>
        </if>
        <if test="ids==null or ids.length==0">
           where 1=2
        </if>
</delete>

从SQL执行性能角度分析,一般在SQL语句中不建议使用in表达式,可以参考如下代码进行实现(重点是forearch中or运算符的应用):

    <delete id="deleteObjects">
       delete from sys_logs
       <choose>
         <when test="ids!=null and ids.length>0">
           <where>
              <foreach collection="ids"
                       item="id"
                       separator="or">
                  id=#{id}
              </foreach>
           </where>
         </when>
         <otherwise>
          where 1=2
         </otherwise>
       </choose>
    </delete>

2:SQL片段的使用

猜你喜欢

转载自blog.csdn.net/KAITUOZHEMJ/article/details/113092604