先看看官网关于标签的描述及例子:
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>
当使用applyCode或applyName进行单个模糊匹配查询时,查询结果无误
当使用applyCode和applyName进行组合模糊匹配查询时,查询结果错误
原以为<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>