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 @ 2023-05-03 16:07  红尘过客2022  阅读(88)  评论(0)    收藏  举报