mybatis where 标签使用

本文介绍MyBatis中where标签的使用技巧,通过对比传统写法与where标签简化后的写法,展示如何避免SQL语句构造时出现的问题,并说明where标签如何智能地处理SQL语句中的条件判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mybatis where 标签

我们经常在动态构造sql时,为防止注入或防止语句不当时会使用where 1=1

<select id="selectGroupByEmployeeNum" resultMap="BaseResultMap" parameterType="com.dao.impl.ZcChatGroup">
  	select
		*
	from 
		zc_chat_group 
	WHERE 1=1
	<if test="id!=null">
		id= #{id} 
	</if>
	<if test="leaderNum!=null">
		and leader_num = #{leaderNum} 
	</if>
	<if test="groupType!=null">
		and group_type = #{groupType} 
	</if>
  </select>

但在使用where标签可以简化这条语句

<select id="selectGroupByEmployeeNum" resultMap="BaseResultMap" parameterType="com.dao.impl.ZcChatGroup">
  	select
		*
	from 
		zc_chat_group 
	<where>
		<if test="id!=null">
			id= #{id} 
		</if>
		<if test="leaderNum!=null">
			and leader_num = #{leaderNum} 
		</if>
		<if test="groupType!=null">
			and group_type = #{groupType} 
		</if>
	</where>
  </select>

这条sql执行时,如果id这个参数为null,则这条语句的执行结果为
select * from zc_chat_group where leader_num = ‘xx’ and group_type = ‘xx’

这个‘where’标签会知道如果它包含的标签中有返回值的话,它就会插入一个‘where’。此外,如果标签返回的内容是以AND 或OR开头的,则会把它去除掉。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值