动态SQL:传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach标签,可组合成非常灵活的SQL语句,从而提高开发人员的效率。
- if:利用if实现简单的条件选择
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
and author=#{author}
</if>
- choose(when,otherwise):相当于java中的switch语句,通常与when和otherwise搭配
相当于Java中的
switch (ch) {
18 case 'B':
19 System.out.println("case one");
20 break;
21 case 'A':
22 System.out.println("case two");
23 break;
24 case 'C':
25 System.out.println("case three");
26 break;
27 }
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
- where:简化Sql语句中where的条件判断
我们需要使用where判断可以过滤传入的错误参数,使用标签代替语句where,而且帮助我们去掉and或者or等连接关键词
<where>
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
author=#{author}
</if>
</where>
官方的解释
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
author=#{author}
</if>
</trim>
这两段代码相同
- set:解决动态更新语句
set标签 如果里面有满足的条件 会自动培杰set标签
后面如果有多余的都好也可以自动去除
<set>
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
author=#{author}
</if>
</set>
where id=#{id}
官方的解释
<trim prefix="SET" suffixOverrides=",">
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
author=#{author}
</if>
</trim>
where id=#{id}
- foreach:迭代一个集合,通常用于in条件
lect id="queryBlogByForeach" resultType="Blog" parameterType="map">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
public void queryBlogByForeach(){
SqlSession session = MyBatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
Map map = new HashMap();
ArrayList<String> ids = new ArrayList<String>();
ids.add("c37b25762c2a4e7493c5ce5234b11327");
ids.add("9e1d1ae65fba48e8aaf13d474e9f1e71");
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogByForeach(map);
}