首页 > 其他 > 详细

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

时间:2021-01-19 19:42:08      阅读:54      评论:0      收藏:0      [点我收藏+]
  1. 在mybatis中拼接查询语句,偶尔会出现where后面可能一个字段的值都没有,就导致所有条件无效,导致where没有存在的意义;但也有可能这些条件会存在。
    • 那解决这个问题的方法,最常见的就是:在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>

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

原文:https://www.cnblogs.com/Twittery/p/14299132.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!