bind标签在mybatis官方文档中只有一句话和一个基本例子进行了介绍,下面是官方文档的介绍:
bind 元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文。比如:
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
value的值写OGNL表达式,OGNL表达式的使用不做过多说明,如果想在OGNL表达式中使用字符串
- 简单写法:用引号扩起来,到底使用单引号还是双引号是由外层引号决定的。
- 标准写法:用%{’’}或%{""}把表达式括起来,强制转成字符串。
在这里value=后面外层使用的双引号,所以内层单引号括起来的’%‘表示的就是字符串’%’
由上面的例子我们可以知道,bind标签的name属性填写一个参数名,value填写这个参数的值(使用OGNL表达式),bind标签写上后,在标签后面的上下文中使用的和bind标签name值同名的参数,它的值就会被替换为bind标签的value的值。如上面的例子中,在执行这条select语句时,#{pattern}的值就会为"’%’ + _parameter.getTitle() + ‘%’"计算执行后的值。
我在实际做项目的时候,遇到了这样的一种情况,在一个select标签中,有多个地方需要用到一个同名的参数,而这个参数需要在这几个地方的值是不一样的。下面是我遇到的情况:
<sql id="sql">
<where>
<if test="flag!=null and flag!=''">
<choose>
<when test="flag == '21'">
and t.flag = 2
and exists(select 1 from table2 t2 where t2.foreignId = t.id and t2.flag = 2)
</when>
<when test="flag == '22'">
and t.flag = 2
and not exists(select 1 from table2 t2 where t2.foreignId = t.id and t2.flag = 2)
</when>
</choose>
</if>
</where>
</sql>
这个sql会根据dao接口传递过来的flag参数来实现条件查询,然后我需要写这样一段代码
<select id="showCount" resultType="map">
select
(select count(*) from table t <include refid="sql"></include>) count1,
(select count(*) from table t <include refid="sql"></include>) count2
from dual
</select>
这段代码的2个地方都引入了sql,如何使flag参数在这两个地方的值不同?
比如在第一个地方使flag的值为21,在第二个地方使flag的值为22。
我曾尝试使用include标签下的property标签来解决这个问题
<select id="showCount" resultType="map">
select
(select count(*) from table t <include refid="sql"><property name="flag" value="21"></property></include>) count1,
(select count(*) from table t <include refid="sql"><property name="flag" value="22"></property></include>) count2
from dual
</select>
但是发现property标签并没有起到作用。似乎在dao接口有参数传递过来的情况下,property标签就失效了,会直接使用dao接口传过来的flag的值。
使用bind标签就解决了我的问题,完善后的代码如下:
<select id="showCount" resultType="map">
select
(select count(*) from table t <bind name="flag" value="'21'" /> <include refid="sql"></include>) count1,
(select count(*) from table t <bind name="flag" value="'22'" /> <include refid="sql"></include>) count2
from dual
</select>
bind标签动态改变了参数flag的值,后写的bind标签会再次赋值