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.h3.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就比较简单了。