:本文转载自南轲梦

注:博主 Chloneda个人博客 | 博客园 | Github | Gitee | 知乎

上篇文章《深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap》简单介绍了mybatis的查询,至此,CRUD都已讲完。本文将介绍mybatis强大的动态SQL。

那么,问题来了: 什么是动态SQL? 动态SQL有什么作用?

传统的使用JDBC的方法,相信大家在组合复杂的的SQL语句的时候,需要去拼接,稍不注意哪怕少了个空格,都会导致错误。Mybatis的动态SQL功能正是为了解决这种问题, 其通过 if, choose, when, otherwise, trim, where, set, foreach标签,可组合成非常灵活的SQL语句,从而提高开发人员的效率。下面就去感受Mybatis动态SQL的魅力吧:

mybatis中if判断

作为程序猿,谁不懂if !在mybatis中也能用 if 啦:

<select id="findUserById" resultType="user">
select * from user where
<if test="id != null">
id=#{id}
</if>
and deleteFlag=0;
</select>

上面例子: 如果传入的id 不为空, 那么才会SQL才拼接id = #{id}。 这个相信大家看一样就能明白,不多说。

细心的人会发现一个问题:“你这不对啊! 要是你传入的id为null, 那么你这最终的SQL语句不就成了 select * from user where and deleteFlag=0, 这语句有问题!”

是啊,这时候,mybatis的 where 标签就该隆重登场啦:

mybatis中where

咱们通过where改造一下上面的例子:

<select id="findUserById" resultType="user">
select * from user
<where>
<if test="id != null">
id=#{id}
</if>
and deleteFlag=0;
</where>
</select>

有些人就要问了: “你这都是些什么玩意儿! 跟上面的相比, 不就是多了个where标签嘛! 那这个还会不会出现 select * from user where and deleteFlag=0 ?”

的确,从表面上来看,就是多了个where标签而已, 不过实质上, mybatis是对它做了处理,当它遇到AND或者OR这些,它知道怎么处理。其实我们可以通过 trim 标签去自定义这种处理规则。

trim:我的地盘,我做主

上面的where标签,其实用trim 可以表示如下:

<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>

它的意思就是: 当WHERE后紧随AND或则OR的时候,就去除AND或者OR。 除了WHERE以外, 其实还有一个比较经典的实现,那就是SET。

set: 信我,不出错

<update id="updateUser" parameterType="com.dy.entity.User">
update user set
<if test="name != null">
name = #{name},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="age != null">
age = #{age}
</if>
<where>
<if test="id != null">
id = #{id}
</if>
and deleteFlag = 0;
</where>
</update>

问题又来了: “如果我只有name不为null, 那么这SQL不就成了 update set name = #{name}, where ........ ? 你那name后面那逗号会导致出错啊!”

是的,这时候,就可以用mybatis为我们提供的set 标签了。下面是通过set标签改造后:

<update id="updateUser" parameterType="com.dy.entity.User">
update user
<set>
<if test="name != null">name = #{name},</if>
<if test="password != null">password = #{password},</if>
<if test="age != null">age = #{age},</if>
</set>
<where>
<if test="id != null">
id = #{id}
</if>
and deleteFlag = 0;
</where>
</update>

这个用trim 可表示为:

<trim prefix="SET" suffixOverrides=",">
...
</trim>

foreach: 你有for, 我有foreach!

java中有for, 可通过for循环, 同样, mybatis中有foreach, 可通过它实现循环,循环的对象当然主要是java容器和数组。

<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>

将一个 List 实例或者数组作为参数对象传给 MyBatis,当这么做的时候,MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键,而数组实例的键将是“array”。同样, 当循环的对象为map的时候,index其实就是map的key。

choose: 我选择了你,你选择了我

Java中有switch, mybatis有choose

<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>

以上例子中: 当title和author都不为null的时候, 那么选择二选一(前者优先), 如果都为null, 那么就选择 otherwise中的, 如果tilte和author只有一个不为null, 那么就选择不为null的那个。

纵观mybatis的动态SQL, 强大而简单, 相信大家简单看一下就能使用了。

好啦,本次就写到这!下篇文章将结合mybatis的源码分析一次sql语句执行的整个过程。


深入浅出Mybatis系列九-强大的动态SQL的更多相关文章

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

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

  2. MyBatis(九):动态SQL

    本文是按照狂神说的教学视频学习的笔记,强力推荐,教学深入浅出一遍就懂!b站搜索狂神说或点击下面链接 https://space.bilibili.com/95256449?spm_id_from=33 ...

  3. 深入浅出Mybatis系列(九)---强大的动态SQL

    上篇文章<深入浅出Mybatis系列(八)---mapper映射文件配置之select.resultMap>简单介绍了mybatis的查询,至此,CRUD都已讲完.本文将介绍mybatis ...

  4. 深入浅出Mybatis系列(九)---强大的动态SQL(转载)

    原文出处:http://www.cnblogs.com/dongying/p/4092662.html 上篇文章<深入浅出Mybatis系列(八)---mapper映射文件配置之select.r ...

  5. 深入浅出Mybatis系列 强大的动态SQL

    上篇文章<深入浅出Mybatis系列(八)---mapper映射文件配置之select.resultMap>简单介绍了mybatis的查询,至此,CRUD都已讲完.本文将介绍mybatis ...

  6. 深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap

    上篇<深入浅出Mybatis系列(七)---mapper映射文件配置之insert.update.delete>介绍了insert.update.delete的用法,本篇将介绍select ...

  7. 深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap good

    上篇<深入浅出Mybatis系列(七)---mapper映射文件配置之insert.update.delete>介绍了insert.update.delete的用法,本篇将介绍select ...

  8. 深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap[转]

    上篇<深入浅出Mybatis系列(七)---mapper映射文件配置之insert.update.delete>介绍了insert.update.delete的用法,本篇将介绍select ...

  9. 深入浅出Mybatis系列八-mapper映射文件配置之select、resultMap

    注:本文转载自南轲梦 注:博主 Chloneda:个人博客 | 博客园 | Github | Gitee | 知乎 上篇<深入浅出Mybatis系列(七)---mapper映射文件配置之inse ...

随机推荐

  1. PS-蒙版的深入解析

    ps四大核心技术是什么?通道.蒙版.路径.选区 通道: 通道的详解,不过比较早的文章了. http://www.blueidea.com/tech/graph/2004/2056.asp PS通道快速 ...

  2. Git的指令

    一,访问本地Git 上一节我们已学会了如何注册GitHub和安装Git 现在先打开电脑终端或Git Bash,首先和Git打个招呼,输入Git 二.新建文件/进入文件夹 mkdir + 文件名    ...

  3. 你知道EasyX吗

    关于C++控制台上的图形界面,你知道一个东西叫做EasyX吗? 作为一个退役的OI选手(WTF?\(3^2-3^1\)年级退役?),在退役之后总想找点事情做. 开发个游戏?(我只会控制台) 学下人工智 ...

  4. const与vector的搭配

    有三种组合方式,分别为: vector<const int> vec; const vector<int> vec; const vector<const int> ...

  5. php gettype()函数

      gettype() 会根据 参数类型返回值: boolean:表示变量为布尔类型 integer:表示变量为整数类型 double :表示变量为float类型(历史原因) string:表示变量为 ...

  6. javascript Worker子线程

    main.js code: //创建 var worker = new Worker("./worker.js"); //发送 worker.postMessage(1); //接 ...

  7. this的使用情况

    this的几种使用情况 1.在普通函数内部,this指向的是window,在严格模式下,this的值是undefined function fun(){ console.log(this); } fu ...

  8. 论文《A Generative Entity-Mention Model for Linking Entities with Knowledge Base》

    A Generative Entity-Mention Model for Linking Entities with Knowledge Base   一.主要方法 提出了一种生成概率模型,叫做en ...

  9. Effective Java, Third Edition

    https://github.com/jbloch/effective-java-3e-source-code 网址是 Effetive java的源码 effective-java-3e-sourc ...

  10. 珠峰-架构6-es6

    let aa = ; { console.log(aa); } // ----- let aa = ; { console.log(aa); // 报错 aa is not defined let a ...