mybatis xml中定义变量_mysql

mybatis定义全局变量只需要配置一下即可,那如何在mybatis xml文件中定义局部变量呢?这就需要使用​​<bind>​​标签了。

bind标签允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。通俗来讲它就是声明了一个局部变量,它的优先级是高于其他语句的。

格式:

<bind name="name" value="value"/>

  • name:定义的变量名称
  • value:value是一个具体的值,它可以是入参,也可以是一个表达式,比如:判断条件

举例

UserInfo实体类

public class UserInfo {
private Long id;
private String gender;
private String name;
private Date createDate;
}

不使用bind标签的SQL语句

<select id="bindTest" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from users
<where>
<choose>
<when test="minId != null and minId > 0 and maxId != null and maxId > 0">
and id between #{minId} and #{maxId}
</when>
<otherwise>
<if test="minId != null and minId > 0">
and id ">>= #{minId}
</if>
</otherwise>
</choose>
<if test="username != null and username.trim() != ''">
and name like concat('%' , #{username} , '%')
</if>
</where>
</select>

测试类

@Test
public void testBind(){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
List<UserInfo> userInfos = userInfoMapper.bindTest(1L , 10L, "0");
System.out.println(userInfos);
}

运行测试类,打印的SQL语句:

sql=select Id, gender , name , create_date from users WHERE id between 1 and 10 and name like concat('%' , '0' , '%')

修改成使用bind标签的SQL语句:

<select id="bindTest" resultMap="BaseResultMap">
<bind name="minIdFlag" value="minId != null and minId > 0"/>
<bind name="maxIdFlag" value="maxId != null and maxId > 0"/>
<bind name="usernameLike" value="'%' + username + '%'"/>

select
<include refid="Base_Column_List" />
from users
<where>
<choose>
<when test="minIdFlag and maxIdFlag">
and id between #{minId} and #{maxId}
</when>
<otherwise>
<if test="minIdFlag">
and id ">>= #{minId}
</if>
</otherwise>
</choose>
<if test="username != null and username.trim() != ''">
and name like #{usernameLike}
</if>
</where>
</select>

运行测试类,打印SQL如下:

sql=select Id, gender , name , create_date from users WHERE id between 1 and 10 and name like '%0%'

对比一下可以发现使用​​<bind>​​​标签前后的sql语句都是一样的,也说明​​<bind>​​标签替换成功。

注意事项

  • bind标签的value不能为null
  • bind标签name最好不要使用点​​·​​​进行赋值操作,如果使用的话直接取值是没问题的, 但是如果在​​<if>​​​、​​<when>​​​等标签中使用时会报​​no getter xx​​异常。

本篇简单介绍了一下​​<bind>​​标签的使用,希望对你有用。

mybatis xml中定义变量_xml_02