赞
踩
MyBatis if 类似于 Java 中的 if 语句,是 MyBatis 中最常用的判断语句。使用 if 标签可以节省许多拼接 SQL 的工作,把精力集中在 XML 的维护上。
if 语句使用方法简单,常常与 test 属性联合使用。语法如下。
当判断条件为 true 时,才会执行所包含的 SQL 语句。
Mybatis if标签可用在许多类型的 SQL 语句中,我们以查询为例。首先看一个很普通的查询:
<!-- 查询用户列表,like用户名称 -->
<select id="getUserListLikeName" parameterType="User" resultMap="userResultMap">
SELECT * from user u
WHERE u.username LIKE CONCAT(CONCAT('%', #{username}),'%')
</select>
但是当 username 或 sex 为 null 时,此语句很可能报错或查询结果为空。此时我们使用 if 动态 sql 语句先进行判断,如果值为 null 或等于空字符串,我们就不进行此条件的判断,增加灵活性。
参数为实体类:User。将实体类中所有的属性均进行判断,如果不为空则执行判断条件。
<!-- 添加 if(判断参数) - 将实体类 User 不为空的属性作为 where 条件 -->
<select id="getUserList" resultMap="resultMap_User" parameterType="com.yiibai.pojo.User">
SELECT u.username,
u.password,
u.sex,
u.birthday,
u.photo,
u.score,
u.sign
FROM user u
WHERE
<if test="username !=null ">
u.username LIKE CONCAT(CONCAT('%', #{username, jdbcType=VARCHAR}),'%')
</if>
<if test="sex!= null and sex != '' ">
AND u.sex = #{Sex, jdbcType=INTEGER}
</if>
<if test="birthday != null ">
AND u.birthday = #{birthday, jdbcType=DATE}
</if>
<if test="userId != null and userId != '' ">
AND id.user_id = #{userId, jdbcType=VARCHAR}
</if>
</select>
使用时比较灵活,创建新的一个这样的实体类,我们需要限制那个条件,只需要附上相应的值就会 where 这个条件,相反不去赋值就可以不在 where 中判断。
public void select_by_if() {
User user = new User();
user.setUsername("");
user.setSex(1);
user.setBirthday(DateUtil.parse("1990-08-18"));
List<User> userList = this.dynamicSqlMapper.getUserList_if(user);
for (user u : userList) {
System.out.println(u.toString());
}
}
我们再看看一下另一个示例,先来看看下面的代码:
<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
select * from t_blog where 1 = 1
<if test="title != null">
and title = #{title}
</if>
<if test="content != null">
and content = #{content}
</if>
<if test="owner != null">
and owner = #{owner}
</if>
</select>
这条语句的意思非常简单,如果提供了 title 参数,那么就要满足 title=#{title},同样如果提供了 Content 和 Owner 的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有 Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用 JDBC 的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼 SQL 语句,这是极其麻烦的,比起来,上述的动态SQL就比较简单了。
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。