MyBatis的动态SQL详解[借鉴].pdfVIP

  • 5
  • 0
  • 约8.17千字
  • 约 8页
  • 2021-10-19 发布于福建
  • 举报
MyBatis 的动态 SQL详解 MyBatis 的动态 SQL 是基于 OGNL 表达式的,它可以帮助我们方便的在 SQL 语句中实现 某些逻辑。 MyBatis 中用于实现动态 SQL 的元素主要有: if choose (when ,otherwise ) trim where set foreach if 就是简单的条件判断, 利用 if 语句我们可以实现某些简单的条件选择。 先来看如下一个例 子: 01 selectid=dynamicIfTestparameterType=BlogresultType=Blog 02 select * from t_blog where 1 = 1 03 iftest=title != null 05 and title = #{title} 06 /if 07 iftest=content != null 08 and content = #{content} 09 /if 10 iftest=owner != null 11 and owner = #{owner} 12 /if 14 /select 这条语句的意思非常简单,如果你提供了 title 参数,那么就要满足 title=#{title} ,同样如果 你提供了 Content 和 Owner 的时候,它们也需要满足相应的条件,之后就是返回满足这些 条件的所有 Blog ,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用 JDBC 的时候,如果我们要达到同样的选择效果的时候,我们就需要拼 SQL 语句,这是极 其麻烦的,比起来,上述的动态 SQL 就要简单多了。 choose 元素的作用就相当于 JAVA 中的 switch 语句,基本上跟 JSTL 中的 choose 的作用 和用法是一样的,通常都是与 when 和 otherwise 搭配的。看如下一个例子: 0 selectid=dynamicChooseTestparameterType=BlogresultType=Blog 1 0 select * from t_blog where 1 = 1 2 03 choose 05 whentest=title != null 06 and title = #{title} 07 /when 08 whentest=content != null 09 and content = #{content} 10 /when 11 otherwise 13 and owner = owner1 14 /otherwise 15 /choose 16 /select when 元素表示当 when 中的条件满足的时候就输出其中的内容, 跟 JAVA 中的 switch 效果 差不多的是按照条件的顺序,当 when 中有条件满足的时候,就会跳出 choose ,即所有的 when 和 otherwise 条件中,只有一个会输出,当所有的我很条件都不满足的时候就输出 otherwise 中的内容。 所以上述语句的意思非常简单, 当 title!=null 的时候就输出 and titlte = #{title} ,不再往下判断条件,当 title 为空且 content!=null 的时候就输出 and content = #{content} ,当所有条件都不满足的时候就输出 otherwise 中的内

文档评论(0)

1亿VIP精品文档

相关文档