mybatis格式化输出标签之where 标签

复制copy是程序员提高效能的核心方式,但是由于有些知识陈旧了,年复一年的复制,

而没有系统的知识学习,并不晓得还有更合理或者更优雅的写法。

1=1 这种东西很多项目很常见,但是应该被放进历史的垃圾桶的。

<select id="getAgentList" resultType="com.wht.demo.dao.vo.AgentVo">  
select
t.node_id as nodeId,
t.host_name as hostName,
t.address_ip as addressIp
from
t_node_agent t
where 1=1
<if test='appId !=null and appId != "" '>
and t.app_id= #{appId}
</if>
<if test='osType!=null and osType!= "" '>
and t.os_type= #{osType}
</if>
</select>

如上SQL,对于传入的查询条件,我们往往是需要空判断。
1、如果没有1=1并且查询条件为空,最后sql就会以where结尾。
2、如果没有1=1 有查询条件传入,也会多一个and关键字导致SQL错误。
最low的方式是 在where 后面带一个 1=1
在运维旧项目的时候,这种写法可以说遍地都是,并不美观。

常用写法应该如下:

<select id="getAgentList" resultType="com.wht.demo.dao.vo.AgentVo">  
select
t.node_id as nodeId,
t.host_name as hostName,
t.address_ip as addressIp
from
t_node_agent t
<where>
<if test='appId !=null and appId != "" '>
and t.app_id= #{appId}
</if>
<if test='osType!=null and osType!= "" '>
and t.os_type= #{osType}
</if>
</where>
</select>

这种写法,就会自动处理where 和and关键字的拼接,确保适配所以参数有无的sql拼接。

posted @   红尘过客2022  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示