mybatis定义全局变量只需要配置一下即可,那如何在mybatis xml文件中定义局部变量呢?这就需要使用<bind>
标签了。
「bind」标签允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。通俗来讲它就是声明了一个局部变量,它的优先级是高于其他语句的。
格式:
<bind name="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>
标签替换成功。
·
进行赋值操作,如果使用的话直接取值是没问题的, 但是如果在<if>
、<when>
等标签中使用时会报no getter xx
异常。本篇简单介绍了一下<bind>
标签的使用,希望对你有用。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有