在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> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 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的设计差异
· 三行代码完成国际化适配,妙~啊~