mybatis 详解(五)------动态SQL


  前面几篇博客我们通过实例讲解了用mybatis对一张表进行的CRUD操作,但是我们发现写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。

  那么怎么去解决这个问题呢?这就是本篇所讲的使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。

  我们以 User 表为例来说明:

  

回到顶部

1、动态SQL:if 语句

  根据 username 和 sex 来查询数据。如果username为空,那么将只根据sex来查询;反之只根据username来查询

  首先不使用 动态SQL 来书写

?
1
2
3
4
5
6
<select id="selectUserByUsernameAndSex"
        resultType="user" parameterType="com.ys.po.User">
    <!-- 这里和普通的sql 查询语句差不多,对于只有一个参数,后面的 #{id}表示占位符,里面不一定要写id,
            写啥都可以,但是不要空着,如果有多个参数则必须写pojo类里面的属性 -->
    select * from user where username=#{username} and sex=#{sex}
</select>

  

  上面的查询语句,我们可以发现,如果 #{username} 为空,那么查询结果也是空,如何解决这个问题呢?使用 if 来判断

?
1
2
3
4
5
6
7
8
9
10
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user where
        <if test="username != null">
           username=#{username}
        </if>
         
        <if test="username != null">
           and sex=#{sex}
        </if>
</select>

  这样写我们可以看到,如果 sex 等于 null,那么查询语句为 select * from user where username=#{username},但是如果usename 为空呢?那么查询语句为 select * from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句

回到顶部

2、动态SQL:if+where 语句

?
1
2
3
4
5
6
7
8
9
10
11
12
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user
    <where>
        <if test="username != null">
           username=#{username}
        </if>
         
        <if test="username != null">
           and sex=#{sex}
        </if>
    </where>
</select>

  这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

  

回到顶部

3、动态SQL:if+set 语句

  同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- 根据 id 更新 user 表的数据 -->
<update id="updateUserById" parameterType="com.ys.po.User">
    update user u
        <set>
            <if test="username != null and username != ''">
                u.username = #{username},
            </if>
            <if test="sex != null and sex != ''">
                u.sex = #{sex}
            </if>
        </set>
     
     where id=#{id}
</update>

  这样写,如果第一个条件 username 为空,那么 sql 语句为:update user u set u.sex=? where id=?

      如果第一个条件不为空,那么 sql 语句为:update user u set u.username = ? ,u.sex = ? where id=?

回到顶部

4、动态SQL:choose(when,otherwise) 语句

  有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User">
      select * from user
      <where>
          <choose>
              <when test="id !='' and id != null">
                  id=#{id}
              </when>
              <when test="username !='' and username != null">
                  and username=#{username}
              </when>
              <otherwise>
                  and sex=#{sex}
              </otherwise>
          </choose>
      </where>
  </select>

  也就是说,这里我们有三个条件,id,username,sex,只能选择一个作为查询条件

    如果 id 不为空,那么查询语句为:select * from user where  id=?

    如果 id 为空,那么看username 是否为空,如果不为空,那么语句为 select * from user where  username=?;

          如果 username 为空,那么查询语句为 select * from user where sex=?

  

回到顶部

5、动态SQL:trim 语句

  trim标记是一个格式化的标记,可以完成set或者是where标记的功能

  ①、用 trim 改写上面第二点的 if+where 语句

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
        select * from user
        <!-- <where>
            <if test="username != null">
               username=#{username}
            </if>
             
            <if test="username != null">
               and sex=#{sex}
            </if>
        </where>  -->
        <trim prefix="where" prefixOverrides="and | or">
            <if test="username != null">
               and username=#{username}
            </if>
            <if test="sex != null">
               and sex=#{sex}
            </if>
        </trim>
    </select>

  prefix:前缀      

  prefixoverride:去掉第一个and或者是or

  ②、用 trim 改写上面第三点的 if+set 语句

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!-- 根据 id 更新 user 表的数据 -->
    <update id="updateUserById" parameterType="com.ys.po.User">
        update user u
            <!-- <set>
                <if test="username != null and username != ''">
                    u.username = #{username},
                </if>
                <if test="sex != null and sex != ''">
                    u.sex = #{sex}
                </if>
            </set> -->
            <trim prefix="set" suffixOverrides=",">
                <if test="username != null and username != ''">
                    u.username = #{username},
                </if>
                <if test="sex != null and sex != ''">
                    u.sex = #{sex},
                </if>
            </trim>
         
         where id=#{id}
    </update>

  suffix:后缀  

  suffixoverride:去掉最后一个逗号(也可以是其他的标记,就像是上面前缀中的and一样)

回到顶部

6、动态SQL: SQL 片段

  有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

  比如:假如我们需要经常根据用户名和性别来进行联合查询,那么我们就把这个代码抽取出来,如下:

?
1
2
3
4
5
6
7
8
9
<!-- 定义 sql 片段 -->
<sql id="selectUserByUserNameAndSexSQL">
    <if test="username != null and username != ''">
        AND username = #{username}
    </if>
    <if test="sex != null and sex != ''">
        AND sex = #{sex}
    </if>
</sql>

  引用 sql 片段

?
1
2
3
4
5
6
7
8
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user
    <trim prefix="where" prefixOverrides="and | or">
        <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
        <include refid="selectUserByUserNameAndSexSQL"></include>
        <!-- 在这里还可以引用其他的 sql 片段 -->
    </trim>
</select>

  注意:①、最好基于 单表来定义 sql 片段,提高片段的可重用性

     ②、在 sql 片段中不要包括 where

    

回到顶部

7、动态SQL: foreach 语句

  需求:我们需要查询 user 表中 id 分别为1,2,3的用户

  sql语句:select * from user where id=1 or id=2 or id=3

       select * from user where id in (1,2,3)

①、建立一个 UserVo 类,里面封装一个 List<Integer> ids 的属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.ys.vo;
import java.util.List;
public class UserVo {
    //封装多个用户的id
    private List<Integer> ids;
    public List<Integer> getIds() {
        return ids;
    }
    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }
}  

②、我们用 foreach 来改写 select * from user where id=1 or id=2 or id=3

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
    select * from user
    <where>
        <!--
            collection:指定输入对象中的集合属性
            item:每次遍历生成的对象
            open:开始遍历时的拼接字符串
            close:结束时拼接的字符串
            separator:遍历对象之间需要拼接的字符串
            select * from user where 1=1 and (id=1 or id=2 or id=3)
          -->
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>

  测试:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//根据id集合查询user表数据
@Test
public void testSelectUserByListId(){
    String statement = "com.ys.po.userMapper.selectUserByListId";
    UserVo uv = new UserVo();
    List<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    ids.add(3);
    uv.setIds(ids);
    List<User> listUser = session.selectList(statement, uv);
    for(User u : listUser){
        System.out.println(u);
    }
    session.close();
}

  

③、我们用 foreach 来改写 select * from user where id in (1,2,3)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">
        select * from user
        <where>
            <!--
                collection:指定输入对象中的集合属性
                item:每次遍历生成的对象
                open:开始遍历时的拼接字符串
                close:结束时拼接的字符串
                separator:遍历对象之间需要拼接的字符串
                select * from user where 1=1 and id in (1,2,3)
              -->
            <foreach collection="ids" item="id" open="and id in (" close=") " separator=",">
                #{id}
            </foreach>
        </where>
    </select>

  

回到顶部

8、总结

  其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。

  

作者:YSOcean
出处:http://www.cnblogs.com/ysocean/
本文版权归作者所有,欢迎转载,但未经作者同意不能转载,否则保留追究法律责任的权利。

分类: JavaWeb
标签: MyBatis详解系列
好文要顶 关注我 收藏该文

YSOcean
关注 - 13
粉丝 - 2453

+加关注

12
0

« 上一篇:mybatis 详解(四)------properties以及别名定义
» 下一篇:mybatis 详解(六)------通过mapper接口加载映射文件

posted @ 2017-08-09 09:03 YSOcean 阅读(49263) 评论(9) 编辑 收藏

回复引用

#1楼 2017-08-09 14:27 PPBoy

写的不错啊,启蒙教材。
支持(0)反对(0)

回复引用

#2楼 2017-08-09 16:20 晃悠人生

不错
支持(0)反对(0)

回复引用

#3楼 2018-01-31 17:57 壹个菜鸟

学习了,收获很大
支持(0)反对(0)

回复引用

#4楼 2018-06-04 16:04 带妳心菲

写的很不错,有个疑问问一下,如下的<script>, <CDATA>的作用是什么,求解答
"<script>" +
"SELECT id,sn,user_id,
"FROM oilcard "+
"<where>" +
"<if test=\"createdStart !=null \"> and created <![CDATA[ > ]]> #{createdStart}</if>" +
"<if test=\"createdEnd !=null \"> and created <![CDATA[ < ]]> #{createdEnd}</if>" +
"</where>" +
"order by order_time desc " +
"</script>"
支持(0)反对(0)

http://pic.cnblogs.com/face/637525/20150826135046.png

回复引用

#5楼[楼主] 2018-06-05 09:19 YSOcean

@ 带妳心菲
sql中有一些特殊的字符的话,在解析xml文件的时候会被转义,<CDATA>能避免被转义。
<script>这个标签到是没用过
支持(0)反对(0)

http://pic.cnblogs.com/face/1120165/20170526223410.png

回复引用

#6楼 2018-06-05 09:46 带妳心菲

嗯嗯,多谢了,之前问过其他人,说<script>也是防止转义,<CDATA>倒是没有使用过,看来作用是一样的,但是感觉这样写很麻烦,一般使用注解在Mapper接口之中写SQL貌似也不需要这些<script>,<CDATA>吧
支持(0)反对(0)

http://pic.cnblogs.com/face/637525/20150826135046.png

回复引用

#7楼 2018-10-15 14:51 帅的很耗cpu

多谢博主
支持(0)反对(0)

http://pic.cnblogs.com/face/1493070/20180929145724.png

回复引用

#8楼 2019-01-02 20:14 一杯热咖啡AAA

师傅,看你一篇博客当看别人几篇博客,讲的真的很好,我要把你的博客看完!
支持(0)反对(0)

回复引用

#9楼41979352019/3/10 0:00:03 2019-03-10 00:00 一只小狼

真心不错,系统全面,清晰易懂,感觉跟教科书级别的一样!
支持(0)反对(0)

刷新评论刷新页面返回顶部
发表评论

昵称:

评论内容:

不改了 退出 订阅评论

[Ctrl+Enter快捷键提交]

【推荐】超50万C++/C#源码: 大型实时仿真组态图形源码
【培训】IT职业生涯指南,Java程序员薪资翻3倍的秘密
【推荐】专业便捷的企业级代码托管服务 - Gitee 码云
相关博文:
· mybatis 详解(五)------动态SQL
· mybatis 详解(五)------动态SQL
· mybatis入门基础(五)----动态SQL
· mybatis详解(五)------动态SQL
· mybatis详解------动态SQL
最新新闻
· 「听音乐、逛评论」之后能不能做成社交?网易云音乐想用小程序试一试
· 马斯克:特斯拉下一代电动跑车充一次电可行驶超过1000公里
· 华为帝国全景
· 你还敢长胖吗?肥胖人群体脂越高脑容量就越小
· 原子对撞机中发现不可能现象:光子之间竟会发生互动
» 更多新闻...

转载于:https://www.cnblogs.com/huanglf714/p/10782893.html

【转载】 mybatis入门系列四之动态SQL相关推荐

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

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

  2. 机器学习入门系列四(关键词:BP神经网络)

    机器学习入门系列四(关键词:BP神经网络) 标签: 机器学习神经网络 2016-01-12 15:28 80人阅读 评论(0) 收藏 举报 本文章已收录于: 分类: 机器学习(3) 作者同类文章X 版 ...

  3. Mybatis的特性详解——动态SQL

    Mybatis的特性详解--动态SQL 前言 一.动态sql的元素 1.MyBatis if标签:条件判断 2.MyBatis choose.when和otherwise标签 3.MyBatis wh ...

  4. Reflex WMS入门系列四十:对某个托盘执行上架,系统不能自动建议货架?

    Reflex WMS入门系列四十:对某个托盘执行上架,系统不能自动建议货架? 如下图示,在Reflex WMS系统里,使用RF枪功能,对于某个托盘685110000000041602执行上架操作.Re ...

  5. mybatis入门(四)之动态SQL

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

  6. Mybatis学习日记(四)——动态SQL第一部分

    Mybatis的强大特性之一是它的动态SQL,在进行项目开发的时候,我们对数据库的操作不可能全部是定式的,当对数据库的操作根据不同情况发生变化时,就可以用到Mybatis的动态SQL.而Mybatis ...

  7. Mybatis中输入输出映射和动态Sql

    一.输入映射 我们通过配置parameterType的值来指定输入参数的类型,这些类型可以是简单数据类型.POJO.HashMap等数据类型 1.简单类型 2.POJO包装类型 ①这是单表查询的时候传 ...

  8. MyBatis之基于XML的动态SQL

    先说下我的梦想,大学的时候一直想着是能开店卖胡辣汤,到目前依然还是我的梦想,上周一家出版社联系我问我有没有时间可以合作出书,这也是我的梦想之一,想了想还是放弃了,至少觉得目前不行,毕竟工作还不到五年, ...

  9. mybatis入门(六)之SQL语句构建器类

    转载自    mybatis SQL语句构建器类 问题 Java程序员面对的最痛苦的事情之一就是在Java代码中嵌入SQL语句.这么来做通常是由于SQL语句需要动态来生成-否则可以将它们放到外部文件或 ...

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

    2019独角兽企业重金招聘Python工程师标准>>> 有些时候,sql语句where条件中,需要一些安全判断,例如按某一条件查询时如果传入的参数是空,此时查询出的结果很可能是空的, ...

最新文章

  1. 满洲里市智慧教育建设跨入云时代
  2. 判断字符串是不是数字
  3. 汇编(8086cpu): 地址寄存器
  4. oracle index contention,Index Contention等待
  5. 8086CPU汇编寻址写法
  6. 邮政银行贷款迟还4个小时就造成信用逾期,如何解决?
  7. SQL Server Query界面不能录入中文
  8. java调用MySQL脚本_Java调用SQL脚本执行常用的方法示例
  9. unity5 静态和动态cubmap
  10. qt中如何使用mysql_qt中如何使用mysql 以及静态编译qt中如何加上mysql(1)
  11. PDF区域文本提取工具
  12. UTF-8字符集中文排序方法研究
  13. 通过ServerGuide 装 服务器 raid1
  14. 计算机考研复试题(近十万字)
  15. 极域电子书包课堂管理系统
  16. JS/JavaScript中的概念区分:global对象、window对象、document对象
  17. Enhancing Label Correlation Feedback in Multi-Label Text Classification via Multi-Task Learning
  18. Java写入txt文件内容
  19. 2022年微信小程序真机调试全流程及10大常见问题处理
  20. 快速提高网站排名工具大全

热门文章

  1. Matlab将底色改为白色
  2. 读卡器 linux 驱动,基于Linux的公交一卡通读卡器驱动设计
  3. 线粒体靶向的纳米递送PCN-224 纳米粒子-瑞禧
  4. 安卓(Android) 刷机教程(任何机型、小米、华为等等)
  5. 在Google上做搜索引擎优化 (SEO),最重要的是哪几点?
  6. pentaho的使用与感受
  7. php调用pentaho,Pentaho数据源和查询
  8. 不租服务器,自建个人商业网站(如何购买域名)
  9. 信息学奥赛一本通1179:奖学金
  10. c语言如何画函数图形,c语言绘制函数曲线