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

引言

动态SQL:Dynamic SQL。

本节我们来通过 MyBatis 的官方文档进行学习。

Description(描述)

官方描述如下:

One of the most powerful features of MyBatis has always been its Dynamic SQL capabilities. If you have any experience with JDBC or any similar framework, you understand how painful it is to conditionally concatenate strings of SQL together, making sure not to forget spaces or to omit a comma at the end of a list of columns. Dynamic SQL can be downright painful to deal with.

While working with Dynamic SQL will never be a party, MyBatis certainly improves the situation with a powerful Dynamic SQL language that can be used within any mapped SQL statement.

The Dynamic SQL elements should be familiar to anyone who has used JSTL or any similar XML based text processors. In previous versions of MyBatis, there were a lot of elements to know and understand. MyBatis 3 greatly improves upon this, and now there are less than half of those elements to work with. MyBatis employs powerful OGNL based expressions to eliminate most of the other elements:

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

My View

上面这段话,总结起来就三点:

  • MyBatis 在动态SQL这块很强大。

  • 你需要会 OGNL 表达式

  • if/choose/trim/foreach

OGNL

用法看这里:OGNL指南

另外,支持转义符,所以,看一下转义:

if/where/trim/choose/foreach

  • if 表示 判断
  <if test="title != null">AND title like #{title}</if>
  • where

我们总会在if标签里写AND,那么当第一个不存在时就会出问题: sql: ...WHERE AND ...

因此 where 是解决这个问题的

  <where><if test="state != null">state = #{state}</if><if test="title != null">AND title like #{title}</if><if test="author != null and author.name != null">AND author_name like #{author.name}</if></where>
  • trim

有人会说了,既然写在前面有问题,那可不可以写在后面呢?当然可以。

来看些 trim 的用法:

<trim prefix="WHERE" prefixOverrides="AND |OR ">...
</trim>-----<trim prefix="SET" suffixOverrides=",">...
</trim>

总结一下: prefix:前面加什么 prefixOverrides:前面忽略掉什么 suffix:后缀 suffixOverrides:后面忽略掉什么

  • choose
  <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>
  • foreach

遍历一个集合。

collection:指定要遍历的集合: list类型的参数会特殊处理封装在map中,map的key就叫list item:将当前遍历出的元素赋值给指定的变量 separator:每个元素之间的分隔符 open:遍历出所有结果拼接一个开始的字符 close:遍历出所有结果拼接一个结束的字符 index:索引。遍历list的时候是index就是索引,item就是当前值

  WHERE ID in<foreach item="item" index="index" collection="list"open="(" separator="," close=")">#{item}</foreach>

set

    <update id="testUpdate">UPDATEuser<set><if test="user.name != null">name = #{user.name},</if><if test="user.age != null and user.age >= 0">age = #{user.age}</if></set><where><if test="user.id != null and user.id > 0">id = #{user.id}</if></where></update>

批量插入

  • 方法一:
    <insert id="testBatchInsert1">INSERT INTOuser(name, age)VALUES<foreach collection="users" index="i" item="k" separator=",">(<if test="k.name != null">#{k.name}</if>,<if test="k.age != null and k.age >= 0">#{k.age}</if>)</foreach></insert>
  • 方法二:
    <insert id="testBatchInsert2"><foreach collection="users" index="i" item="k" separator=";">INSERT INTOuser(name, age)VALUES(<if test="k.name != null">#{k.name}</if>,<if test="k.age != null and k.age >= 0">#{k.age}</if>)</foreach></insert>

注意

1、数据库的url应该如下配置:

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_demo?allowMultiQueries=true

2、此方法返回的影响行数不正确。

==> Preparing: INSERT INTO user(name, age) VALUES( ? , ? ) ; INSERT INTO user(name, age) VALUES( ? , ? ) ==> Parameters: n3(String), 11(Integer), n4(String), 12(Integer) <== Updates: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@64fc097e] rs num : 1

_parameter and _databaseId

_parameter,参数 _databaseId,当前数据库的Id

bind

关于数据绑定,MyBatis官网提供的例子如下:

<select id="selectBlogsLike" resultType="Blog"><bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />SELECT * FROM BLOGWHERE title LIKE #{pattern}
</select>

引用sql

有些重复的,可以抽取出来

后记

测试代码:DynamicSQL-Demo

需要说明的是:为了保持测试风格,有些返回值类型不正确,导致测试报错,但这并不影响着一节的学习,因为你能够看到sql和结果。

转载于:https://my.oschina.net/fengwenyi/blog/1801918

【MyBatis】学习纪要六:动态SQL相关推荐

  1. MyBatis:学习笔记(4)——动态SQL

    MyBatis:学习笔记(4)--动态SQL 转载于:https://www.cnblogs.com/MrSaver/p/7453949.html

  2. mybatis学习7之动态sql

    动态sql环境搭建和数据准备 工具类,获取UUID package com.shan.utils;import org.junit.Test;import java.util.UUID;public ...

  3. Mybatis学习笔记之---动态sql中标签的使用

    动态Sql语句中标签的使用 (一)常用标签 1.<if> if标签通常用于WHERE语句中,通过判断参数值来决定是否使用某个查询条件, 他也经常用于UPDATE语句中判断是否更新某一个字段 ...

  4. Mybatis学习笔记13 - 动态sql之set标签

    示例代码: 接口定义: package com.mybatis.dao;import com.mybatis.bean.Employee;public interface EmployeeMapper ...

  5. Java神鬼莫测之MyBatis注解开发之动态SQL语句(六)

    1.Mybatis注解开发之动态SQL语句 背景:使用mybatis的注解开发动态Sql会比较麻烦, 很不方便, 所以不太推荐使用,该文章以查询作为案例,演示动态sql语句. 注意:Mybatis的动 ...

  6. 【Java从0到架构师】MyBatis - 增删改、动态 SQL

    MyBatis - 增删改.动态 SQL 动态 SQL if 标签 where 标签 sql 标签 foreach 标签 添加 主键设置 批量添加 - 利用 foreach 标签 更新 删除 批量删除 ...

  7. JavaWeb学习笔记(动态SQL)

    JavaWeb学习笔记(动态SQL) 动态SQL中的元素 < if>元素 < choose>.< when>.< otherwise>元素 < w ...

  8. Mybatis系列全解(八):Mybatis的9大动态SQL标签你知道几个?提前致女神!

    封面:洛小汐 作者:潘潘 2021年,仰望天空,脚踏实地. 这算是春节后首篇 Mybatis 文了~ 跨了个年感觉写了有半个世纪 - 借着女神节 ヾ(◍°∇°◍)ノ゙ 提前祝男神女神们越靓越富越嗨森! ...

  9. SSM框架开发web项目系列(四) MyBatis之快速掌握动态SQL

    前言 通过前面的MyBatis部分学习,已经可以使用MyBatis独立构建一个数据库程序,基本的增删查改/关联查询等等都可以实现了.简单的单表操作和关联查询在实际开的业务流程中一定会有,但是可能只会占 ...

最新文章

  1. 花5分钟看这篇之前,你才发现你不懂RESTful
  2. notepad++ 设置常用快捷键
  3. 如何用python画数据图-用Python绘制地理图
  4. 用matlab生成ASK FSK PSK,通信原理课程设计(matlab实现ASK FSK PSK).doc
  5. linux配置ip地址 suse_suse linux中为单网卡配置多IP的方法
  6. python异常数据处理_Python爬虫提高之异常处理
  7. 从架构设计理念到集群部署,全面认识KubeEdge
  8. SpringBoot目录
  9. qcustomplot时间坐标轴画直线_为什么鸡看到画直线会晕?
  10. Pdproxy度盘下载器
  11. maximo开发经验
  12. html js中英切换,使用js实现URL中的中英文转化 - 小俊学习网
  13. jquery点击图片放大,再点缩小(转)
  14. mysql动态规划_关于动态规划的描述,不正确的是( )
  15. 80端口进不去问题解析
  16. HOUDINI TIP | USING HOU MODULE IN VISUAL STUDIO CODE_手动在vscode里设置houdiniPython模块
  17. python合成图片_python图片合成的示例
  18. epic启动器在哪个文件夹_启动时|原神启动器在哪个文件中 启动器文件位置一览_234游戏网...
  19. ElasticSearch 之初步上手
  20. 博洛尼亚大学计算机科学,2021QS世界大学学科排名重磅发布!意大利大学详细上榜排名,不容错过!...

热门文章

  1. NPAPI开发详解,Windows版
  2. c语言多维数组指针地址讲解,C语言入门之多维数组的指针变量
  3. 使用mybatis-generator自动生成model、dao、mapping文件
  4. 蓝桥杯 错误票据 (stringstream的使用)
  5. SrpingCloud 之SrpingCloud config分布式配置中心
  6. [bzoj1088]扫雷
  7. mongoDB的shell数组操作器
  8. 五千字详解消息通知!
  9. 一文全解析——APP版本管理基本知识
  10. 一份厘清「数据指标」问题的清单