http://elim.iteye.com/blog/1338557
基础部分可以查看我的另一篇博客:http://haohaoxuexi.iteye.com/blog/1333271
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。
MyBatis中用于实现动态SQL的元素主要有:
- if
- choose(when,otherwise)
- trim
- where
- set
- foreach
if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。先来看如下一个例子:
- <select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
- select * from t_blog where 11 = 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就要简单多了。
choose元素的作用就相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常都是与when和otherwise搭配的。看如下一个例子:
- <select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
- select * from t_blog where 11 = 1
- <choose>
- <when test="title != null">
- and title = #{title}
- </when>
- <when test="content != null">
- and content = #{content}
- </when>
- <otherwise>
- and owner = "owner1"
- </otherwise>
- </choose>
- </select>
when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时候,就会跳出choose,即所有的when和otherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的内容。所以上述语句的意思非常简单, 当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。
where语句的作用主要是简化SQL语句中where中的条件判断的,先看一个例子,再解释一下where的好处。
- <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 给忽略。
trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能,示例代码如下:
- <select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
- select * from t_blog
- <trim prefix="where" prefixOverrides="and |or">
- <if test="title != null">
- title = #{title}
- </if>
- <if test="content != null">
- and content = #{content}
- </if>
- <if test="owner != null">
- or owner = #{owner}
- </if>
- </trim>
- </select>
如果
content!= null,生成的sql语句为
select * from t_blog where content = xxxx
set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段。下面是一段示例代码:
- <update id="dynamicSetTest" parameterType="Blog">
- update t_blog
- <set>
- <if test="title != null">
- title = #{title},
- </if>
- <if test="content != null">
- content = #{content},
- </if>
- <if test="owner != null">
- owner = #{owner}
- </if>
- </set>
- where id = #{id}
- </update>
上述示例代码中,如果set中一个条件都不满足,即set中包含的内容为空的时候就会报错。
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:
- 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key
下面分别来看看上述三种情况的示例代码:
1.单参数List的类型:
- <select id="dynamicForeachTest" resultType="Blog">
- select * from t_blog where id in
- <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
上述collection的值为list,对应的Mapper是这样的
- public List<Blog> dynamicForeachTest(List<Integer> ids);
测试代码:
- @Test
- public void dynamicForeachTest() {
- SqlSession session = Util.getSqlSessionFactory().openSession();
- BlogMapper blogMapper = session.getMapper(BlogMapper.class);
- List<Integer> ids = new ArrayList<Integer>();
- ids.add(1);
- ids.add(3);
- ids.add(6);
- List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
- for (Blog blog : blogs)
- System.out.println(blog);
- session.close();
- }
2.单参数array数组的类型:
- <select id="dynamicForeach2Test" resultType="Blog">
- select * from t_blog where id in
- <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
上述collection为array,对应的Mapper代码:
- public List<Blog> dynamicForeach2Test(int[] ids);
对应的测试代码:
- @Test
- public void dynamicForeach2Test() {
- SqlSession session = Util.getSqlSessionFactory().openSession();
- BlogMapper blogMapper = session.getMapper(BlogMapper.class);
- int[] ids = new int[] {1,3,6,9};
- List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
- for (Blog blog : blogs)
- System.out.println(blog);
- session.close();
- }
3.自己把参数封装成Map的类型
- <select id="dynamicForeach3Test" resultType="Blog">
- select * from t_blog where title like "%"#{title}"%" and id in
- <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
- #{item}
- </foreach>
- </select>
上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
- public List<Blog> dynamicForeach3Test(Map<String, Object> params);
对应测试代码:
- @Test
- public void dynamicForeach3Test() {
- SqlSession session = Util.getSqlSessionFactory().openSession();
- BlogMapper blogMapper = session.getMapper(BlogMapper.class);
- final List<Integer> ids = new ArrayList<Integer>();
- ids.add(1);
- ids.add(2);
- ids.add(3);
- ids.add(6);
- ids.add(7);
- ids.add(9);
- Map<String, Object> params = new HashMap<String, Object>();
- params.put("ids", ids);
- params.put("title", "中国");
- List<Blog> blogs = blogMapper.dynamicForeach3Test(params);
- for (Blog blog : blogs)
- System.out.println(blog);
- session.close();
- }
基础部分可以查看我的另一篇博客:
http://haohaoxuexi.iteye.com/blog/1333271
基于3.3.1版本验证的新特性
本文是基于Mybatis 3.0.6版本所写,笔者最近在查看新版Mybatis(3.3.1)时发现其对动态SQL的支持较以前的3.0.6版本的区别不大,基本一致,但笔者还是发现有以下新特性:
1、foreach标签遍历的集合元素类型是Map.Entry类型时,index属性指定的变量代表对应的Map.Entry的key,item属性指定的变量代表对应的Map.Entry的value。此时如果对应的集合是Map.entrySet,则对应的collection属性用collection。foreach在进行遍历的时候如果传入的参数是List类型,则其collection属性的值可以是list或collection,但如果传入的参数是Set类型,则collection属性的值只能用collection。
- <select id="dynamicForeachTest" resultType="Blog">
- select * from t_blog where id in
- <!-- 遍历的对象是Map.Entry时,index代表对应的key,item代表对应的value -->
- <foreach collection="collection" index="key" item="value" open="(" separator="," close=")">
- #{key}, #{value}
- </foreach>
- </select>
- public List<Blog> dynamicForeachTest(Set<Map.Entry<Integer, Integer>> ids);
2、
bind标签,动态SQL中已经包含了这样一个新的标签,它的功能是在当前OGNL上下文中创建一个变量并绑定一个值。有了它以后我们以前的模糊查询就可以改成这个样子:
- <select id="fuzzyQuery" resultType="Blog" parameterType="java.lang.String">
- <!-- bind标签用于创建新的变量 -->
- <bind name="titleLike" value="'%'+_parameter+'%'"/>
- select * from t_blog where title like #{titleLike}
- </select>
1、动态SQL的元素:
<select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> </select>
这条语句会提供一个可选的文本查找功能。如果你没有传递title,那么所有激活的博客都会被返回。但是如果你传递了title,那么就会查找相近的title(对于敏锐的检索,这中情况下你的参数值需要包含任意的遮掩或通配符)的博客。
假若我们想可选地搜索title 和author呢?首先,要改变语句的名称让它有意义。然后 简单加入另外的一个条件。
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
有时我们不想应用所有的条件, 相反我们想选择很多情况下的一种。Java 中的switch和语句相似,MyBatis提供choose元素。
我们使用上面的示例,但是现在我们来搜索当title提供时仅有title 条件,当author提 供时仅有author条件。如果二者都没提供,只返回featured blogs。
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <choose> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </select>
【注:choose语句中的when是只要满足一个条件之后就放弃继续比较了,比较方式同Java中的Switch语句类似。】
考虑,多个动态查询条件情况:
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG WHERE <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </select>
如果这些条件都没有匹配上将会发生什么?这条 SQL 结束时就会成这样:
SELECT * FROM BLOG WHERE
这会导致查询失败。如果仅仅第二个条件匹配是什么样的?这条 SQL 结束时就会是这 样:
SELECT * FROM BLOG WHERE AND title like ‘someTitle’
这个查询也会失败。这个问题不能简单的用条件来解决,如果你从来没有这样写过,那 么你以后也不会这样来写。
MyBatis 有一个简单的处理,这在 90%的情况下都会有用。而在不能使用的地方,你可 以自定义处理方式。加上一个简单的改变,所有事情都会顺利进行:
<select id="findActiveBlogLike" resultType="Blog"> SELECT * FROM BLOG <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND author_name like #{author.name} </if> </where> </select>
where 元素知道如果由被包含的标记返回任意内容,就仅仅插入“WHERE” 。而且,如 果以“AND”或“OR”开头的内容,那么就会跳过WHERE不插入。
如果 where 元素没有做出你想要的,你可以使用 trim 元素来自定义。比如,和 where 元素相等的
trim元素是:
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
prefixOverrides属性采用管道文本分隔符来覆盖, 这里的空白也是重要的。它的结果就是移除在prefixOverrides属性中指定的内容,插入在with属性中的内容。
和动态更新语句相似的解决方案是
set。set元素可以被用于动态包含更新的列,而不包含不需更新的。比如:
<update id="updateAuthorIfNecessary"> update Author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set> where id=#{id} </update>
这里,set 元素会动态前置 SET 关键字,而且也会消除任意无关的逗号,那也许在应用 条件之后来跟踪定义的值。
如果你对和这相等的trim元素好奇,它看起来就是这样的:
<trim prefix="SET" suffixOverrides=","> ... </trim>
注意这种情况下我们覆盖一个后缀,而同时也附加前缀。
另外一个动态SQL通用的必要操作是迭代一个集合, 通常是构建在IN条件中的。
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
foreach 元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可 以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素 是很智能的,它不会偶然地附加多余的分隔符。
注意 你可以传递一个 List 实例或者数组作为参数对象传给MyBatis。当你这么做的时候,MyBatis会自动将它包装在一个Map中,用名称在作为键。List实例将会以“list” 作为键,而数组实例将会以“array”作为键。
bind元素允许你在自定义变量(不用符合OGNL规范),并且应用到上下文中。例如:
<select id="selectBlogsLike" resultType="Blog"> <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" /> SELECT * FROM BLOG WHERE title LIKE #{pattern} </select>