【Mybatis】Mybatis中避免where空条件后面添加1=1 优化方法

在mybatis中拼接查询语句,偶尔会出现where后面可能一个字段的值都没有,就导致所有条件无效,导致where没有存在的意义;但也有可能这些条件会存在。

  1. 占位符
    • 那解决这个问题的方法,最常见的就是:在where后面添加1=1
    <select id="findByConnectorPrice" parameterType="com.hlht.evcs.bean.ConnectorPriceRelation"
            resultMap="BaseResultMap">
        select
        p.customer_operator_id,
        p.connector_id,
        p.template_id,
        p.relate_time,
        p.charge_operator_id
        from
        in_connector_price_relation p
        where 1=1
        <if test="CustomerOperatorId != null and CustomerOperatorId!='' ">
            and p.customer_operator_id = #{CustomerOperatorId}
        </if>
        <if test="ConnectorId != null and ConnectorId!='' ">
            and p.connector_id = #{ConnectorId}
        </if>
        order by ${RelateTime} desc
    </select>

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

  1. 占位符
    • 所以正确的做法应该是:使用标签 解决这个问题
    • where标签会自动处理第一个为null时候的and问题
<select id="findByConnectorPrice" parameterType="com.hlht.evcs.bean.ConnectorPriceRelation"
            resultMap="BaseResultMap">
        select
        p.customer_operator_id,
        p.connector_id,
        p.template_id,
        p.relate_time,
        p.charge_operator_id
        from
        in_connector_price_relation p
        <where>
            <if test="CustomerOperatorId != null and CustomerOperatorId!='' ">
                and p.customer_operator_id = #{CustomerOperatorId}
            </if>
            <if test="ConnectorId != null and ConnectorId!='' ">
                and p.connector_id = #{ConnectorId}
            </if>
        </where>
        order by p.relate_time desc limit 1
    </select>
原文地址:https://www.cnblogs.com/Twittery/p/14299132.html