<bind>
标签可以使用ONGL(Object-Graph Navigation Language, 对象图形化导航语言)表达式创建一个变量并将其绑定到上下文中。如以下代码:
<if test="userName != null and userName != ''">
and user_name like concat('%', #{userName} ,'%')
</if>
由于不同的数据库,concat函数的用法不一样,Mysql的有3个参数,而oracle的只有2个。这就造成了这条SQL在不同环境中运行可能会出错。为了避免这种错误,可以用<bind>
标签,如下:
<if test="userName != null and userName != ''">
<bind name="nameLike" value="'%' + userName + '%'"/>
and user_name like #{nameLike}
</if>
<bind>
标签的两个属性都是必选的,name为绑定到上下文的变量名,value为OGNL表达式。创建了<bind>
标签的变量后,就可以在下面直接使用了。如下例子,先写一个静态方法,然后在Mapper.xml中调用该方法设置默认值:
package ex.mybatis.rbac.mapper;
public class BindTest {
public static String setName() {
return "test";
}
}
Mapper.xml
<!-- 动态根据输入的用户名和id查询用户信息<choose>标签用法 -->
<select id="selectByIdOrName" resultMap="BaseResultMap">
<!-- 使用<bind>标签调用的方法拿出来的默认值 -->
<bind name="name" value="@ex.mybatis.rbac.mapper.BindTest@setName()"/>
select id, user_name, user_password, user_email, create_time, user_info, head_img
from sys_user
<!-- 加上1=1是为了防止2个查询条件都为空的时候,SQL不会报错。学了where标签后可以去掉 -->
where 1=1
<choose>
<when test="id != null">
and id = #{id}
</when>
<when test="userName != null and userName != ''">
and user_name like concat('%', #{userName} ,'%')
</when>
<otherwise>
<!-- 当所有条件都空时,使用<bind>标签调用的方法拿出来的默认值 -->
and user_name=#{name}
</otherwise>
</choose>
</select>
使用<bind>
标签打印入参信息,如下:
package ex.mybatis.rbac.mapper;
public class BindTest {
public static void print(Object param) {
System.out.println(param);
}
}
- 在Mapper.xml中使用
<bind>
标签,调用该方法
<!-- <foreach>标签实现更新,参数为map -->
<update id="updateByMap">
<bind name="print" value="@ex.mybatis.rbac.mapper.BindTest@print(_parameter)"/>
update sys_user
set
<foreach collection="_parameter" item="val" index="key" separator=",">
${key} = #{val}
</foreach>
where id = #{id}
</update>
{[email protected], user_password=1111333, id=1001}
通过这种方式就能实现一些特殊的功能,上面的例子只是为了启发大家,不要乱用。