mybatis where 标签使用

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开头的,则会把它去除掉。

  • 6
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值