当前位置: 首页 > news >正文

MyBatis的动态SQL详解

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。

MyBatis中用于实现动态SQL的元素主要有:

 

  • if
  • choose(when,otherwise)
  • trim
  • where
  • set
  • foreach
if就是简单的条件判断,利用if语句我们可以实现某些简单的条件选择。先来看如下一个例子:
Xml代码    收藏代码
  1. <select id="dynamicIfTest" parameterType="Blog" resultType="Blog">  
  2.     select * from t_blog where 11 = 1  
  3.     <if test="title != null">  
  4.         and title = #{title}  
  5.     </if>  
  6.     <if test="content != null">  
  7.         and content = #{content}  
  8.     </if>  
  9.     <if test="owner != null">  
  10.         and owner = #{owner}  
  11.     </if>  
  12. </select>  
这条语句的意思非常简单,如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能,以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了。

choose元素的作用就相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常都是与when和otherwise搭配的。看如下一个例子:
Xml代码    收藏代码
  1. <select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">  
  2.     select * from t_blog where 11 = 1   
  3.     <choose>  
  4.         <when test="title != null">  
  5.             and title = #{title}  
  6.         </when>  
  7.         <when test="content != null">  
  8.             and content = #{content}  
  9.         </when>  
  10.         <otherwise>  
  11.             and owner = "owner1"  
  12.         </otherwise>  
  13.     </choose>  
  14. </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的好处。
Xml代码    收藏代码
  1. <select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">  
  2.     select * from t_blog   
  3.     <where>  
  4.         <if test="title != null">  
  5.             title = #{title}  
  6.         </if>  
  7.         <if test="content != null">  
  8.             and content = #{content}  
  9.         </if>  
  10.         <if test="owner != null">  
  11.             and owner = #{owner}  
  12.         </if>  
  13.     </where>  
  14. </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元素的功能,示例代码如下:
Xml代码    收藏代码
  1. <select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">  
  2.     select * from t_blog   
  3.     <trim prefix="where" prefixOverrides="and |or">  
  4.         <if test="title != null">  
  5.             title = #{title}  
  6.         </if>  
  7.         <if test="content != null">  
  8.             and content = #{content}  
  9.         </if>  
  10.         <if test="owner != null">  
  11.             or owner = #{owner}  
  12.         </if>  
  13.     </trim>  
  14. </select>  
 
set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段。下面是一段示例代码:
Xml代码    收藏代码
  1. <update id="dynamicSetTest" parameterType="Blog">  
  2.     update t_blog  
  3.     <set>  
  4.         <if test="title != null">  
  5.             title = #{title},  
  6.         </if>  
  7.         <if test="content != null">  
  8.             content = #{content},  
  9.         </if>  
  10.         <if test="owner != null">  
  11.             owner = #{owner}  
  12.         </if>  
  13.     </set>  
  14.     where id = #{id}  
  15. </update>  
 上述示例代码中,如果set中一个条件都不满足,即set中包含的内容为空的时候就会报错。

foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:
  1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
  2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key
下面分别来看看上述三种情况的示例代码:
1.单参数List的类型:
Xml代码    收藏代码
  1. <select id="dynamicForeachTest" resultType="Blog">  
  2.     select * from t_blog where id in  
  3.     <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
  4.         #{item}  
  5.     </foreach>  
  6. </select>  
 上述collection的值为list,对应的Mapper是这样的
Java代码    收藏代码
  1. public List<Blog> dynamicForeachTest(List<Integer> ids);  
 测试代码:
Java代码    收藏代码
  1. @Test   
  2. public void dynamicForeachTest() {  
  3.     SqlSession session = Util.getSqlSessionFactory().openSession();  
  4.     BlogMapper blogMapper = session.getMapper(BlogMapper.class);  
  5.     List<Integer> ids = new ArrayList<Integer>();  
  6.     ids.add(1);  
  7.     ids.add(3);  
  8.     ids.add(6);  
  9.     List<Blog> blogs = blogMapper.dynamicForeachTest(ids);  
  10.     for (Blog blog : blogs)  
  11.         System.out.println(blog);  
  12.     session.close();  
  13. }  
 
2.单参数array数组的类型:
Xml代码    收藏代码
  1. <select id="dynamicForeach2Test" resultType="Blog">  
  2.     select * from t_blog where id in  
  3.     <foreach collection="array" index="index" item="item" open="(" separator="," close=")">  
  4.         #{item}  
  5.     </foreach>  
  6. </select>  
 上述collection为array,对应的Mapper代码:
Java代码    收藏代码
  1. public List<Blog> dynamicForeach2Test(int[] ids);  
 对应的测试代码:
Java代码    收藏代码
  1. @Test   
  2. public void dynamicForeach2Test() {  
  3.     SqlSession session = Util.getSqlSessionFactory().openSession();  
  4.     BlogMapper blogMapper = session.getMapper(BlogMapper.class);  
  5.     int[] ids = new int[] {1,3,6,9};  
  6.     List<Blog> blogs = blogMapper.dynamicForeach2Test(ids);  
  7.     for (Blog blog : blogs)  
  8.         System.out.println(blog);  
  9.     session.close();  
  10. }  
 
3.自己把参数封装成Map的类型
Xml代码    收藏代码
  1. <select id="dynamicForeach3Test" resultType="Blog">  
  2.     select * from t_blog where title like "%"#{title}"%" and id in  
  3.     <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">  
  4.         #{item}  
  5.     </foreach>  
  6. </select>  
上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
Java代码    收藏代码
  1. public List<Blog> dynamicForeach3Test(Map<String, Object> params);  
  对应测试代码:
Java代码    收藏代码
  1. @Test   
  2. public void dynamicForeach3Test() {  
  3.     SqlSession session = Util.getSqlSessionFactory().openSession();  
  4.     BlogMapper blogMapper = session.getMapper(BlogMapper.class);  
  5.     final List<Integer> ids = new ArrayList<Integer>();  
  6.     ids.add(1);  
  7.     ids.add(2);  
  8.     ids.add(3);  
  9.     ids.add(6);  
  10.     ids.add(7);  
  11.     ids.add(9);  
  12.     Map<String, Object> params = new HashMap<String, Object>();  
  13.     params.put("ids", ids);  
  14.     params.put("title""中国");  
  15.     List<Blog> blogs = blogMapper.dynamicForeach3Test(params);  
  16.     for (Blog blog : blogs)  
  17.         System.out.println(blog);  
  18.     session.close();  
  19. }  
 

转载于:https://my.oschina.net/javatour/blog/63870

相关文章:

  • 目标模型和现实模型
  • 在pictureBox中拖动图片的实现代码
  • linux-文件类型
  • dll分析
  • 选择Drupal的10大理由
  • argc argv 的使用
  • 劣质电源线引发的硬盘故障
  • struts2常用标签
  • ip_vs实现分析(3)
  • linux 系统基础知识 - 卷管理
  • 解决 umount 时出现的 Device is busy
  • silverlight 在主流浏览器中的问题
  • RAID中的Stripe size对性能的影响?
  • 为何转向Spine.js的十个理由
  • win7下没有注册类别 (异常来自 HRESULT:0x80040154 (REGDB_E_CLASSNOTREG))
  • 【剑指offer】让抽象问题具体化
  • Asm.js的简单介绍
  • github从入门到放弃(1)
  • isset在php5.6-和php7.0+的一些差异
  • Linux CTF 逆向入门
  • ViewService——一种保证客户端与服务端同步的方法
  • vue总结
  • weex踩坑之旅第一弹 ~ 搭建具有入口文件的weex脚手架
  • 不用申请服务号就可以开发微信支付/支付宝/QQ钱包支付!附:直接可用的代码+demo...
  • 关键词挖掘技术哪家强(一)基于node.js技术开发一个关键字查询工具
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 前端技术周刊 2018-12-10:前端自动化测试
  • 前端技术周刊 2019-01-14:客户端存储
  • 如何选择开源的机器学习框架?
  • 三分钟教你同步 Visual Studio Code 设置
  • 学习HTTP相关知识笔记
  • 一文看透浏览器架构
  • 鱼骨图 - 如何绘制?
  • 【云吞铺子】性能抖动剖析(二)
  • # 深度解析 Socket 与 WebSocket:原理、区别与应用
  • #include到底该写在哪
  • (3)选择元素——(14)接触DOM元素(Accessing DOM elements)
  • (搬运以学习)flask 上下文的实现
  • (第一天)包装对象、作用域、创建对象
  • (十二)python网络爬虫(理论+实战)——实战:使用BeautfulSoup解析baidu热搜新闻数据
  • (转)winform之ListView
  • (转载)虚函数剖析
  • .NET C#版本和.NET版本以及VS版本的对应关系
  • .Net7 环境安装配置
  • .NetCore Flurl.Http 升级到4.0后 https 无法建立SSL连接
  • .NET开发不可不知、不可不用的辅助类(三)(报表导出---终结版)
  • .net图片验证码生成、点击刷新及验证输入是否正确
  • .net下简单快捷的数值高低位切换
  • .Net下使用 Geb.Video.FFMPEG 操作视频文件
  • @AliasFor注解
  • @test注解_Spring 自定义注解你了解过吗?
  • [ web基础篇 ] Burp Suite 爆破 Basic 认证密码
  • [100天算法】-目标和(day 79)
  • [GDMEC-无人机遥感研究小组]无人机遥感小组-000-数据集制备
  • [HTML]Web前端开发技术18(HTML5、CSS3、JavaScript )HTML5 基础与CSS3 应用——喵喵画网页