在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>
但是這種做法有一個最大的弊端,就是導致數據表上的索引失效,如果有索引的話。而且還是一個垃圾條件。
- 占位符
- 所以正確的做法應該是:使用
標簽 解決這個問題
- 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>