当 where 中的条件使用的 if 标签较多时,这样的组合可能会导致错误。当 java 代码按如下方法调用时:
@test public void select_test_where() { user user = new user(); user.setusername(null); user.setsex(1); list<user> userlist = this.dynamicsqlmapper.getusertlist_where(user); for (user u : userlist ) { system.out.println(u.tostring()); } }
如果上面例子,参数 username 为 null,将不会进行列 username 的判断,则会直接导“where and”关键字多余的错误 sql。
这时可以使用 where 动态语句来解决。“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以 and 或or 开头的,则它会剔除掉。
上面例子修改为:
<select id="getuserlist_whereif" resultmap="resultmap_user" parametertype="com.h3.pojo.user"> select u.user_id, u.username, u.sex, u.birthday 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> </where> </select>
where 主要是用来简化 sql 语句中 where 条件判断,自动地处理 and/or 条件。
<select id="dynamicwheretest" parametertype="blog" resulttype="blog"> select * from t_blog <where> <if test="title != null"> title = #{title} </if> <if test="content != null"> and content = #{content} </if> <if test="owner != null"> and owner = #{owner} </if> </where> </select>
where 元素的作用是会在写入 where 元素的地方输出一个 where,另外一个好处是你不需要考虑 where 元素里面的条件输出是什么样子的,mybatis 会智能的帮处理,如果所有的条件都不满足那么 mybatis 就会查出所有的记录,如果输出后是 and 开头的,mybatis 会把第一个and忽略,当然如果是 or 开头的,mybatis 也会把它忽略;此外,在 where 元素中你不需要考虑空格的问题,mybatis 会智能的帮你加上。像上述例子中,如果 title=null, 而 content != null,那么输出的整个语句会是 select * from t_blog where content = #{content},而不是 select * from t_blog where and content = #{content},因为 mybatis 会自动地把首个 and / or 给忽略。