MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法

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

  • if
  • choose(when,otherwise)
  • trim
  • where
  • set
  • foreach

1、if

对属性进行判断,如果不为空则执行判断条件

[html] view
plain
copy

  1. <select id="selectByCriteria" parameterType="com.mucfc.dto.Student" resultMap="BaseResultMap">
  2. select * from t_student
  3. where
  4. <if test="stuId != null and stuId !=''">
  5. STU_ID = #{stuId}
  6. </if>
  7. <if test="stuName != null and stuName !=''" >
  8. and STU_NAME = #{stuName}
  9. </if>
  10. <if test="stuClass != null and stuClass !=''">
  11. and STU_CLASS = #{stuClass}
  12. </if>
  13. <if test="stuSex != null and stuSex !=''">
  14. and STU_SEX=#{stuSex}
  15. </if>
  16. <if test="stuAge != null and stuAge !=''">
  17. and STU_AGE=#{stuAge}
  18. </if>
  19. </select>

来看看结果:

这是从web页面输入的参数

这是输出的结果

这是打印出来的Sql语句

从结果可以看出,只有在条件不为空的时候,属性才会赋值。

2、where

当where中的条件使用的if标签较多时,这样的组合可能会导致错误。我们以在1中的查询语句为例子,当输入参数stuId为空时,就会报错

然后是输出的结果:

此时SQL语句变成了select * from t_student    where                   and STU_SEX=?这样会报错

如果上面例子,参数stuId为null,将不会进行STUDENT_NAME列的判断,则会直接导“WHERE AND”关键字多余的错误SQL。这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

可以改成如下:

[html] view
plain
copy

  1. <select id="selectByCriteria" parameterType="com.mucfc.dto.Student" resultMap="BaseResultMap">
  2. select * from t_student
  3. <where>
  4. <if test="stuId != null and stuId !=''">
  5. STU_ID = #{stuId}
  6. </if>
  7. <if test="stuName != null and stuName !=''" >
  8. and STU_NAME = #{stuName}
  9. </if>
  10. <if test="stuClass != null and stuClass !=''">
  11. and STU_CLASS = #{stuClass}
  12. </if>
  13. <if test="stuSex != null and stuSex !=''">
  14. and STU_SEX=#{stuSex}
  15. </if>
  16. <if test="stuAge != null and stuAge !=''">
  17. and STU_AGE=#{stuAge}
  18. </if>
  19. </where>
  20. </select>

再来看看,输入查询条件

然后输出结果

打印出来的SQL语句

- ==>  Preparing: select * from t_student WHERE STU_SEX=? 

==> Parameters: 男(String)

 <==      Total: 14

说明结果是正确的。如果它包含的标签中有返回值的话就插入一个where。此外如果标签返回的内容是以AND或OR开头的,则它会剔除掉。

3、set

当update语句中没有使用if标签时,如果有一个参数为null,都会导致错误。

当在update语句中使用if标签时,如果前面的if没有执行,则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号。

使用if+set标签修改后,如果某项为null则不进行更新,而是保持数据库原值。如下示例:

4、trim

trim是更灵活的去处多余关键字的标签,他可以实践where和set的效果。

[html] view
plain
copy

  1. <select id="selectByCriteria" parameterType="com.mucfc.dto.Student" resultMap="BaseResultMap">
  2. select * from t_student
  3. <trim prefix="where" prefixOverrides="AND|OR">
  4. <if test="stuId != null and stuId !=''">
  5. STU_ID = #{stuId}
  6. </if>
  7. <if test="stuName != null and stuName !=''" >
  8. and STU_NAME = #{stuName}
  9. </if>
  10. <if test="stuClass != null and stuClass !=''">
  11. and STU_CLASS = #{stuClass}
  12. </if>
  13. <if test="stuSex != null and stuSex !=''">
  14. and STU_SEX=#{stuSex}
  15. </if>
  16. <if test="stuAge != null and stuAge !=''">
  17. and STU_AGE=#{stuAge}
  18. </if>
  19. </trim>
  20. </select>

首先判断是否需要where,如果需要,它会自动判断如果where后面有and或者or,就自动把它们都去掉。prefix是前置的,还有suffix是后置的。

如下输入查找参数stuclass=2。

看看打印出来的语句

suffix是后置的例子

[html] view
plain
copy

  1. <insert id="insert" parameterType="com.mucfc.dto.Student" >
  2. insert into t_student
  3. <trim prefix="(" suffix=")" suffixOverrides="," >
  4. <if test="stuId != null" >
  5. STU_ID,
  6. </if>
  7. <if test="stu_name!= null" >
  8. STU_NAME,
  9. </if>
  10. </trim>
  11. <trim prefix="values (" suffix=")" suffixOverrides="," >
  12. <if test="stuId  != null" >
  13. #{stuId},
  14. </if>
  15. <if test="stu_name != null" >
  16. #{stu_name},
  17. </if>
  18. <pre name="code" class="html"> </insert</pre><br>

这里是自动判断是否为空,然后去掉逗号

[html] view
plain
copy

  1. prefix="(" suffix=")"

会自动判断是否需要加上()这个符号

5、choose



        有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。而使用if标签时,只要test中的表达式为true,就会执行if标签中的条件。MyBatis提供了choose 元素。if标签是与(and)的关系,而choose比傲天是或(or)的关系。

        choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则choose结束。当choose中所有when的条件都不满则时,则执行otherwise中的sql。类似于Java 的switch 语句,choose为switch,when为case,otherwise则为default。

[html] view
plain
copy

  1. <!-- 满足其中一个条件时候用choose when操作 -->
  2. <select id="selectByCriteria" parameterType="com.mucfc.dto.Student" resultMap="BaseResultMap">
  3. select * from t_student
  4. <where>
  5. <choose>
  6. <when test="stuId != null and stuId !=''">
  7. STU_ID = #{stuId}
  8. </when>
  9. <when test="stuClass != null and stuClass !=''">
  10. and STU_CLASS = #{stuClass}
  11. </when>
  12. <otherwise>
  13. </otherwise>
  14. </choose>
  15. </where>
  16. </select>

输入两个参数

这里会跳过王五这个参数,因为stuId不为空

然后看打印了来的语句,果然只有一个条件,所以说明是对的

foreach



        对于动态SQL 非常必须的,主是要迭代一个集合,通常是用于IN 条件。List 实例将使用“list”做为键,数组实例以“array” 做为键。

foreach元素是非常强大的,它允许你指定一个集合,声明集合项和索引变量,它们可以用在元素体内。它也允许你指定开放和关闭的字符串,在迭代之间放置分隔符。这个元素是很智能的,它不会偶然地附加多余的分隔符。

注意:你可以传递一个List实例或者数组作为参数对象传给MyBatis。当你这么做的时候,MyBatis会自动将它包装在一个Map中,用名称在作为键。List实例将会以“list”作为键,而数组实例将会以“array”作为键。

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的类型:

[html] view
plain
copy

  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] view
plain
copy

  1. public List<Blog> dynamicForeachTest(List<Integer> ids);

测试代码:

[java] view
plain
copy

  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数组的类型:

[java] view
plain
copy

  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] view
plain
copy

  1. public List<Blog> dynamicForeach2Test(int[] ids);

对应的测试代码:

[java] view
plain
copy

  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的类型

[java] view
plain
copy

  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] view
plain
copy

  1. public List<Blog> dynamicForeach3Test(Map<String, Object> params);

对应测试代码:

[java] view
plain
copy

  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. }

6、联合实例:

[html] view
plain
copy

  1. <insert id="batchInsertTrxBillDetailInfo" parameterType="java.util.Map" >
  2. INSERT ALL
  3. <foreach collection="list" item="item">
  4. into TRX_BILL_DETAIL_INFO
  5. <trim prefix="(" suffix=")" suffixOverrides="," >
  6. <if test="item.id != null" >
  7. ID,
  8. </if>
  9. <if test="item.custNo != null" >
  10. CUST_NO,
  11. </if>
  12. <if test="item.transCode != null" >
  13. TRANS_CODE,
  14. </if>
  15. <if test="item.transRefno != null" >
  16. TRANS_REFNO,
  17. </if>
  18. <if test="item.transSeqno != null" >
  19. TRANS_SEQNO,
  20. </if>
  21. <if test="item.orderNo != null" >
  22. ORDER_NO,
  23. </if>
  24. <if test="item.transAmt != null" >
  25. TRANS_AMT,
  26. </if>
  27. <if test="item.billDate != null" >
  28. BILL_DATE,
  29. </if>
  30. <if test="item.billFlag != null" >
  31. BILL_FLAG,
  32. </if>
  33. <if test="item.transDesc != null" >
  34. TRANS_DESC,
  35. </if>
  36. </trim>
  37. <trim prefix="values (" suffix=")" suffixOverrides="," >
  38. <if test="item.id != null" >
  39. #{item.id,jdbcType=DECIMAL},
  40. </if>
  41. <if test="item.custNo != null" >
  42. #{item.custNo,jdbcType=CHAR},
  43. </if>
  44. <if test="item.transCode != null" >
  45. #{item.transCode,jdbcType=CHAR},
  46. </if>
  47. <if test="item.transRefno != null" >
  48. #{item.transRefno,jdbcType=CHAR},
  49. </if>
  50. <if test="item.transSeqno != null" >
  51. #{item.transSeqno,jdbcType=VARCHAR},
  52. </if>
  53. <if test="orderNo != null" >
  54. #{item.orderNo,jdbcType=CHAR},
  55. </if>
  56. <if test="item.transAmt != null" >
  57. #{item.transAmt,jdbcType=DECIMAL},
  58. </if>
  59. <if test="item.billDate != null" >
  60. #{item.billDate,jdbcType=DECIMAL},
  61. </if>
  62. <if test="item.billFlag != null" >
  63. #{item.billFlag,jdbcType=CHAR},
  64. </if>
  65. <if test="item.transDesc != null" >
  66. #{item.transDesc,jdbcType=VARCHAR},
  67. </if>
  68. </trim>
  69. </foreach>
  70. select 1 from dual
  71. </insert>

MyBatis学习总结(11)——MyBatis动态Sql语句的更多相关文章

  1. MyBatis学习 之 三、动态SQL语句

    目录(?)[-] 三动态SQL语句 selectKey 标签 if标签 if where 的条件判断 if set 的更新语句 if trim代替whereset标签 trim代替set choose ...

  2. MyBatis学习 之 四、动态SQL语句

    有些时候,sql语句where条件中,需要一些安全判断,例如按某一条件查询时如果传入的参数是空,此时查询出的结果很可能是空的,也许我们需要参数为空时,是查出全部的信息.使用Oracle的序列.mysq ...

  3. Mybatis学习(8)动态sql语句

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

  4. Mybatis 系列9-强大的动态sql 语句

    [Mybatis 系列10-结合源码解析mybatis 执行流程] [Mybatis 系列9-强大的动态sql 语句] [Mybatis 系列8-结合源码解析select.resultMap的用法] ...

  5. mybatis学习笔记四(动态sql)

    直接贴图,注解在代码上,其他的配置文件在学习一中就不贴了 1 数据库 2 实体类 package com.home.entity; /** * 此类是: 用户实体类 * @author hpc * @ ...

  6. mybatis学习(九)——动态sql

    MyBatis 的强大特性之一便是它的动态 SQL.可以根据不同条件拼接 SQL 语句. 动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似.主要由以下几种元素. if wh ...

  7. MyBatis学习(二)、SQL语句映射文件(2)增删改查、参数、缓存

    二.SQL语句映射文件(2)增删改查.参数.缓存 2.2 select 一个select 元素非常简单.例如: <!-- 查询学生,根据id --> <select id=" ...

  8. MyBatis学习(二)、SQL语句映射文件(1)resultMap

    二.SQL语句映射文件(1)resultMap SQL 映射XML 文件是所有sql语句放置的地方.需要定义一个workspace,一般定义为对应的接口类的路径.写好SQL语句映射文件后,需要在MyB ...

  9. mybatis 学习四(下) SQL语句映射文件增删改查、参数、缓存

    2.2 select 一个select 元素非常简单.例如: <!-- 查询学生,根据id --> <select id="getStudent" paramet ...

  10. Mybatis学习总结三(动态SQL)

    通过mybatis提供的各种标签方法实现动态拼接sql. 一.if 和 where <select id="findUserList" parameterType=" ...

随机推荐

  1. Https个人总结

    花了一个星期终于搞懂了.. HTTPS个人总结: 一.RSA算法 公钥:可以分发给任意的钥匙 私钥:自己保留起来,不分发给别人的钥匙 RSA算法: 找出质数p.q n = p*q Φ(n)=(p-1) ...

  2. bzoj 1088 [SCOI2005] 扫雷

    SCOI2005 扫雷 一道很有趣的(水)题 “这道题有四种解法,你知道么” 给你矩阵的第二列的数字,求出第一列雷有多少种可能的摆法. 不懂扫雷规则的自行按win+R然后输入winmine 思考过后我 ...

  3. 是我太天真之被BUG按在地上疯狂摩擦

    事情是这样的,我是一个追求完美的人,特别喜欢锦上添花,去年在学习python的时候做了一个作业:多重剪贴板,今天大概是吃饱了,查了一下自己的头发以后,我觉得可以挑战一下自己,所以决定为那个小程序添加一 ...

  4. 安装虚拟机(VM)(一)

    原创作品,允许转载,转载时请务必声明作者信息和本声明.  https://www.cnblogs.com/zhu520/p/10728248.html 本人小白,有错指出.谢谢! 一:安装虚拟机前奏 ...

  5. 安卓Gallery配合ImageSwitcher不显示图片

    Gallary装的是缩略图(thumb),ImageSwitcher装的是大图. 不显示图片的一个可能原因是gallery没设置代理器,另一个原因是没使用相对布局. GalleryActivity.j ...

  6. URAL 1513. Lemon Tale(简单的递推)

    写几组数据就会发现规律了啊. .但是我是竖着看的.. .还找了半天啊... 只是要用高精度来写,水题啊.就当熟悉一下java了啊. num[i] = 2*num[i-1]-num[i-2-k]. 15 ...

  7. Android设计模式(十二)--抽象工厂模式

    问题: 抽象工厂模式,是一个,狠恶心的模式,那么这个模式在Android有没实用到过呢? 1.定义: 抽象工厂模式:为创建一组相关或者是相互依赖的对象提供一个接口,而不须要指定他们的详细类. 2.使用 ...

  8. swust oj 2516 教练我想学算术 dp+组合计数

    #include<stdio.h> #include<string.h> #include<iostream> #include<string> #in ...

  9. legend---一、如何实现js跳转到php页面

    legend---一.如何实现js跳转到php页面 一.总结 一句话总结:url还是同样的方式,只不过注意引号内嵌的时候的转义. 代码: onClick="javascript:if(con ...

  10. WCF项目启动时错误处理

    1. 原因:启动有wcf服务的项目时,报错,是因为wcf的服务没有启动. 解决办法:启动wcf的服务端口,127.0.0:4000,错误消失.