【MapSheep】
[好记性不如烂笔头]
posts - 228,comments - 15,views - 17万

在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>
posted on   (Play)  阅读(1026)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~

点击右上角即可分享
微信分享提示