1. MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。
  2.  
  3. MyBatis中用于实现动态SQL的元素主要有:
  4.  
  5. if
  6. choosewhenotherwise
  7. trim
  8. where
  9. set
  10. foreach
  11.  
  12. if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。先来看如下一个例子:
  13. 01 <select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
  14. 02 select * from t_blog where 1 = 1
  15. 03 <if test="title != null">
  16. 04
  17. 05 and title = #{title}
  18. 06 </if>
  19. 07 <if test="content != null">
  20. 08 and content = #{content}
  21. 09 </if>
  22. 10 <if test="owner != null">
  23. 11 and owner = #{owner}
  24. 12 </if>
  25. 13
  26. 14 </select>
  27. 这条语句的意思非常简单,如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了ContentOwner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了。
  28.  
  29. choose元素的作用就相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常都是与whenotherwise搭配的。看如下一个例子:
  30. 01 <select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
  31. 02 select * from t_blog where 1 = 1
  32. 03 <choose>
  33. 04
  34. 05 <when test="title != null">
  35. 06 and title = #{title}
  36. 07 </when>
  37. 08 <when test="content != null">
  38. 09 and content = #{content}
  39. 10 </when>
  40. 11 <otherwise>
  41. 12
  42. 13 and owner = "owner1"
  43. 14 </otherwise>
  44. 15 </choose>
  45. 16 </select>
  46. when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时候,就会跳出choose,即所有的whenotherwise条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出otherwise中的内容。所以上述语句的意思非常简单, title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。
  47.  
  48. where语句的作用主要是简化SQL语句中where中的条件判断的,先看一个例子,再解释一下where的好处。
  49. 01 <select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">
  50. 02 select * from t_blog
  51. 03 <where>
  52. 04 <if test="title != null">
  53. 05 title = #{title}
  54. 06 </if>
  55. 07 <if test="content != null">
  56. 08
  57. 09 and content = #{content}
  58. 10 </if>
  59. 11 <if test="owner != null">
  60. 12 and owner = #{owner}
  61. 13 </if>
  62. 14 </where>
  63. 15 </select>
  64. 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 给忽略。
  65.  
  66. trim元素的主要功能是可以在自己包含的内容前加上某些前缀,也可以在其后加上某些后缀,与之对应的属性是prefixsuffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverridessuffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能,示例代码如下:
  67. 01 <select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
  68. 02 select * from t_blog
  69. 03 <trim prefix="where" prefixOverrides="and |or">
  70. 04
  71. 05 <if test="title != null">
  72. 06 title = #{title}
  73. 07 </if>
  74. 08 <if test="content != null">
  75. 09 and content = #{content}
  76. 10 </if>
  77. 11 <if test="owner != null">
  78. 12
  79. 13 or owner = #{owner}
  80. 14 </if>
  81. 15 </trim>
  82. 16 </select>
  83. set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段。下面是一段示例代码:
  84. 01 <update id="dynamicSetTest" parameterType="Blog">
  85. 02 update t_blog
  86. 03 <set>
  87. 04 <if test="title != null">
  88. 05 title = #{title},
  89. 06 </if>
  90. 07 <if test="content != null">
  91. 08
  92. 09 content = #{content},
  93. 10 </if>
  94. 11 <if test="owner != null">
  95. 12 owner = #{owner}
  96. 13 </if>
  97. 14 </set>
  98. 15 where id = #{id}
  99. 16 </update>
  100. 上述示例代码中,如果set中一个条件都不满足,即set中包含的内容为空的时候就会报错。
  101.  
  102. foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有itemindexcollectionopenseparatorcloseitem表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:
  103.  
  104. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
  105. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  106. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,mapkey就是参数名,所以这个时候collection属性值就是传入的Listarray对象在自己封装的map里面的key
  107.  
  108. 下面分别来看看上述三种情况的示例代码:
  109. 1.单参数List的类型:
  110. 1 <select id="dynamicForeachTest" resultType="Blog">
  111. 2 select * from t_blog where id in
  112. 3 <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
  113. 4 #{item}
  114. 5 </foreach>
  115. 6
  116. 7 </select>
  117. 上述collection的值为list,对应的Mapper是这样的
  118. 1 public List<Blog> dynamicForeachTest(List<Integer> ids);
  119. 测试代码:
  120. 01 @Test
  121. 02 public void dynamicForeachTest() {
  122. 03 SqlSession session = Util.getSqlSessionFactory().openSession();
  123. 04 BlogMapper blogMapper = session.getMapper(BlogMapper.class);
  124. 05 List<Integer> ids = new ArrayList<Integer>();
  125. 06 ids.add(1);
  126. 07 ids.add(3);
  127. 08 ids.add(6);
  128. 09 List<Blog> blogs = blogMapper.dynamicForeachTest(ids);
  129. 10 for (Blog blog : blogs)
  130. 11 System.out.println(blog);
  131. 12 session.close();
  132. 13 }
  133. 2.单参数array数组的类型:
  134. 1 <select id="dynamicForeach2Test" resultType="Blog">
  135. 2 select * from t_blog where id in
  136. 3 <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
  137. 4 #{item}
  138. 5 </foreach>
  139. 6 </select>
  140. 上述collectionarray,对应的Mapper代码:
  141. 1 public List<Blog> dynamicForeach2Test(int[] ids);
  142. 对应的测试代码:
  143. 01 @Test
  144. 02 public void dynamicForeach2Test() {
  145. 03 SqlSession session = Util.getSqlSessionFactory().openSession();
  146. 04 BlogMapper blogMapper = session.getMapper(BlogMapper.class);
  147. 05 int[] ids = new int[] {1,3,6,9};
  148. 06 List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);
  149. 07 for (Blog blog : blogs)
  150. 08 System.out.println(blog);
  151. 09 session.close();
  152. 10 }
  153. 3.自己把参数封装成Map的类型
  154. 1 <select id="dynamicForeach3Test" resultType="Blog">
  155. 2 select * from t_blog where title like "%"#{title}"%" and id in
  156. 3 <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
  157. 4 #{item}
  158. 5 </foreach>
  159. 6
  160. 7 </select>
  161. 上述collection的值为ids,是传入的参数Mapkey,对应的Mapper代码:
  162. 1 public List<Blog> dynamicForeach3Test(Map<String, Object> params);
  163. 对应测试代码:
  164. 查看源码
  165. 打印?
  166. 01 @Test
  167. 02 public void dynamicForeach3Test() {
  168. 03 SqlSession session = Util.getSqlSessionFactory().openSession();
  169. 04 BlogMapper blogMapper = session.getMapper(BlogMapper.class);
  170. 05 final List<Integer> ids = new ArrayList<Integer>();
  171. 06 ids.add(1);
  172. 07 ids.add(2);
  173. 08 ids.add(3);
  174. 09 ids.add(6);
  175. 10 ids.add(7);
  176. 11 ids.add(9);
  177. 12 Map<String, Object> params = new HashMap<String, Object>();
  178. 13 params.put("ids", ids);
  179. 14 params.put("title", "中国");
  180. 15 List<Blog> blogs = blogMapper.dynamicForeach3Test(params);
  181. 16 for (Blog blog : blogs)
  182. 17 System.out.println(blog);
  183. 18 session.close();
  184. 19 }

mybatis——动态sql的更多相关文章

  1. mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句

    mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. c ...

  2. 9.mybatis动态SQL标签的用法

    mybatis动态SQL标签的用法   动态 SQL MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么 ...

  3. 自己动手实现mybatis动态sql

    发现要坚持写博客真的是一件很困难的事情,各种原因都会导致顾不上博客.本来打算写自己动手实现orm,看看时间,还是先实现一个动态sql,下次有时间再补上orm完整的实现吧. 用过mybatis的人,估计 ...

  4. Mybatis动态SQL单一基础类型参数用if标签

    Mybatis动态SQL单一基础类型参数用if标签时,test中应该用 _parameter,如: 1 2 3 4 5 6 <select id="selectByName" ...

  5. 超全MyBatis动态SQL详解!( 看完SQL爽多了)

    MyBatis 令人喜欢的一大特性就是动态 SQL. 在使用 JDBC 的过程中, 根据条件进行 SQL 的拼接是很麻烦且很容易出错的. MyBatis 动态 SQL 的出现, 解决了这个麻烦. My ...

  6. Mybatis动态SQL简单了解 Mybatis简介(四)

    动态SQL概况 MyBatis 的强大特性之一便是它的动态 SQL 在Java开发中经常遇到条件判断,比如: if(x>0){ //执行一些逻辑........ }   Mybatis应用中,S ...

  7. mybatis原理分析学习记录,mybatis动态sql学习记录

    以下个人学习笔记,仅供参考,欢迎指正. MyBatis 是支持定制化 SQL.存储过程以及高级映射的持久层框架,其主要就完成2件事情: 封装JDBC操作 利用反射打通Java类与SQL语句之间的相互转 ...

  8. mybatis 动态sql和参数

    mybatis 动态sql 名词解析 OGNL表达式 OGNL,全称为Object-Graph Navigation Language,它是一个功能强大的表达式语言,用来获取和设置Java对象的属性, ...

  9. MyBatis动态SQL之一使用 if 标签和 choose标签

    bootstrap react https://segmentfault.com/a/1190000010383464 xml 中 < 转义 to thi tha <if test=&qu ...

  10. MyBatis动态SQL(认真看看, 以后写SQL就爽多了)

    目录 0 一起来学习 mybatis 1 数据准备 2 if 标签 2.1 在 WHERE 条件中使用 if 标签 2.1.1 查询条件 2.1.2 动态 SQL 2.1.3 测试 2.2 在 UPD ...

随机推荐

  1. Unity3D ShaderLab 车辆喷漆光照模型实战

    这一篇,我们来创建一个车辆喷漆的光照模型.首先就是准备场景,新建Shader & Material. 过程比较简单,直接看完成的代码吧: Shader "91YGame/CarOut ...

  2. 使用Inno Setup 打包.NET程序,并自动安装.Net Framework

    使用Inno Setup 打包.NET程序,并自动安装.Net Framework http://www.cnblogs.com/xiaogangqq123/archive/2012/03/19/24 ...

  3. Linux Qt动态库的创建和使用

    一.创建动态库 编写一个共享库类,比如: //..base.h class Base : public QObject { Q_OBJECT public: ); void PrintLog(QStr ...

  4. Valid Parentheses

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  5. dedecms SQL数据库连接信息注解(借鉴)

    <?php $cfg_dbhost = 'localhost'; //数据库地址,这里的localhost指的是本机$cfg_dbname = 'hunuo'; //数据库名$cfg_dbuse ...

  6. Apache搭建多个站点方法详解

    www.111cn.net 编辑:Bolshevik 来源:转载 Apache的虚拟主机是一种允许在同一台机器上配置多个不同站点的web服务器环境的,就是iis一样可以创建多站点了,但是apache需 ...

  7. 学习iOS的一些网站收藏

    1,CocoaChina:http://www.cocoachina.com/ 2,Code4App:http://code4app.com/ 3,梦维:http://www.dreamingwish ...

  8. Mvc3.0_笔记

    1.保留文本框中的值:<p>Find @Html.TextBox("searchKey", ViewBag.Filter as string)</p>  这 ...

  9. 1-2 ISO/OSI七层模型简介

    相关名词解释: ISO:国际标准化组织 OSI:开放系统互联模型 IOS:苹果操作系统, 但是在计算机网络中,IOS是互联网操作系统,是思科公司为其网络设备开发的操作维护系统 <1>OSI ...

  10. CSS3卡片旋转效果

    HTML: <div id="rotate"> <div id="rotate_wrap"> <div id="fron ...