【Bug】MyBatis多个字段进行模糊匹配导致查询不到数据

先看看官网关于标签的描述及例子:

bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文

<select id="selectBlogsLike" resultType="Blog">
	<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
	SELECT * FROM BLOG
		WHERE title LIKE #{pattern}
</select>

通过例子可以看出,<bind />标签创建了一个变量,变量名为name属性的值pattern,在SQL中使用该变量的方式为#{pattern}

官网的例子中只有一个字段进行模糊匹配,而在实际项目中一个SQL可能会有多个字段需要进行模糊匹配

接下来看一个项目中的例子:

<select id="queryBusinessApply" parameterType="BusinessApply" resultType="BusinessApply">
	select business_type,apply_code,apply_name from db_c_business_apply
	<trim prefix="WHERE" prefixOverrides="AND">
		<if test="businessType != null and businessType != ''">
			and business_type = #{businessType}
		</if>
		<if test="applyCode != null and applyCode != ''">
			<bind name="pattern" value="'%' + applyCode + '%'" />
				and apply_code like #{pattern}
		</if>
		<if test="applyName != null and applyName != ''">
			<bind name="pattern" value="'%' + applyName + '%'" />
				and apply_name like #{pattern}
		</if>
	</trim>
</select>

当使用applyCodeapplyName进行单个模糊匹配查询时,查询结果无误
当使用applyCodeapplyName进行组合模糊匹配查询时,查询结果错误

原以为<bind />标签是在<if></if>内部,故两个<bind />标签的name属性值一致不会有问题,实际却是有影响的,修改name属性值使其在一个SQL中保持唯一,调整后的SQL如下:

<select id="queryBusinessApply" parameterType="BusinessApply" resultType="BusinessApply">
	select business_type,apply_code,apply_name from db_c_business_apply
	<trim prefix="WHERE" prefixOverrides="AND">
		<if test="businessType != null and businessType != ''">
			and business_type = #{businessType}
		</if>
		<if test="applyCode != null and applyCode != ''">
			<bind name="applyCodeLike" value="'%' + applyCode + '%'" />
				and apply_code like #{applyCodeLike}
		</if>
		<if test="applyName != null and applyName != ''">
			<bind name="applyNameLike" value="'%' + applyName + '%'" />
				and apply_name like #{applyNameLike}
		</if>
	</trim>
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值