mybatis中使用bind标签更改上下文中参数变量的值

本文介绍了MyBatis中的bind标签,用于在XML映射文件中创建变量并绑定到上下文。通过示例解释了如何使用bind改变参数值,解决了在动态SQL中同一参数在不同位置需要不同值的问题。当include标签的property无法实现需求时,bind标签提供了解决方案。

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

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表达式中使用字符串

  1. 简单写法:用引号扩起来,到底使用单引号还是双引号是由外层引号决定的。
  2. 标准写法:用%{’’}或%{""}把表达式括起来,强制转成字符串。

在这里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标签会再次赋值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值