mybatis实战教程之八动态sql语句.docVIP

  • 4
  • 0
  • 约6.21千字
  • 约 7页
  • 2016-08-27 发布于重庆
  • 举报
mybatis实战教程之八动态sql语句

mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句 mybatis 的动态sql语句是基于OGNL表达式的。可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类: 1. if 语句 (简单的条件判断) 2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似. 3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀) 4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误) 5. set (主要用于更新时) 6. foreach (在实现 mybatis in 语句查询时特别有用) 下面分别介绍这几种处理方式 1. mybaits if 语句处理 ?程序代码 ??? select id=dynamicIfTest parameterType=Blog resultType=Blog ??????? select * from t_blog where 1 = 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就要简单多了 2.2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似 ?程序代码 ??? select id=dynamicChooseTest parameterType=Blog resultType=Blog ??????? select * from t_blog where 1 = 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中的内容。 3.trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀) ?程序代码 ??? select id=dynamicTrimTest parameterType=Blog resultType=Blog ??????? select * from t_blog? ??????? trim prefix=where prefixOverrides=and |or ??????????? if test=title != null ?????

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档