百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

Mybatis系列-5-动态SQL(mybatis中文网)

bigegpt 2024-08-03 11:47 8 浏览

今天再努力一下,没准明天会更好呢?

演示版本为Mybatis最新版本3.5.9。不同版本效果可能不一样。

一、什么是动态SQL

动态SQL说白了就是根据不同条件拼接而成的一个可执行SQL语句。

动态SQL的实现是通过MyBatis提供的各种标签对查询条件做出判断实现动态拼接SQL语句的过程,其条件判断是通过OGNL表达式实现。常用的标签有<if/>、<where/>、<foreach/>等。

注意:当在mapper中使用动态SQL时,如果SQL中出现了诸如>(大于)、<(小于)、>=(大于等于)、<=(小于等于)等符号时,最好使用实体符号。否则,XML可能会出现解析错误的情况,因为mapper配置文件中标签是<>拼接的。

二、常用标签演示

演示版本为Mybatis最新版本3.5.9。不同版本效果可能不一样。

1.if标签

if标签的执行,当test的值为true时,会将其包含的SQL片段拼接到SQL语句中;反之,不拼接。

 <select id="findProInfoTestIf" parameterType="com.shpe.chapter3.entity.ProductInfo" resultType="com.shpe.chapter3.entity.ProductInfo">
     select * from product_info WHERE 1=1
     <if test="proNo!=null and proNo!=''">
         and pro_No=#{proNo}
     </if>
 </select>

2.where 标签

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

将上边的if标签的SQL变形如下:

 <select id="findProInfoTestWhere" parameterType="com.shpe.chapter3.entity.ProductInfo" resultType="com.shpe.chapter3.entity.ProductInfo">
     select * from product_info
     <where>
         <if test="proNo!=null and proNo!=''">
             and pro_No=#{proNo}
         </if>
     </where>
 </select>

3.choose、when、otherwise

choose、when、otherwise这三个标签是一个整体,就像switch....case(含break)...default。

这几个标签的关系是:

  • <choose/>标签只可以包含<when/>、<otherwise/>
  • <choose/>可以包含多个<wher/>标签与一个<otherwise>标签。
  • <choose/>标签的执行,其会从第一个<when/>标签开始,逐个向后进行条件判断。若出现某个<when/>中的test属性值为true,则会直接结束<choose/>标签,不再执行其它<when/>标签。若所有的<when/>的test属性的值为false,则最后执行<otherwise/>标签。
 <select id="findProInfoTestChoose" parameterType="com.shpe.chapter3.entity.ProductInfo" resultType="com.shpe.chapter3.entity.ProductInfo">
     <bind name="proNo1" value="'%' + _parameter.getProNo() + '%'" />
     select * from product_info
     <where>
         <choose>
             <!--%与#占位符之间必须有空格,不然查不到-->
             <when test="proNo=='1'.toString()">
                 and pro_No like #{proNo1}
             </when>
             <when test='proNo=="2"'>
                 and pro_No like '%' #{proNo} '%'
             </when>
             <otherwise>
                 1=2
             </otherwise>
         </choose>
     </where>
 </select>

另外,如果判断条件的值是纯数字,但实际是字符串,上边给出了两种字符串比较的方法。

<when test="proNo=='1'.toString()">;<when test='proNo=="2"'>

4.foreach标签

该标签主要用于实现对数组或集合的遍历。常用属性有:

collection:表示传入过来的参数的数据类型。该参数为必选。要做 foreach 的对象,作为入参时,大致可分为以下三种情况:

(1).如果传入的是单参数且参数类型是一个List集合,collection属性值为【arg0或collection或 list】 .

(2).如果传入的是单参数且参数类型是一个array数组,collection的属性值为【array或arg0 】.

(3).如果传入的参数是多个,此时最好是将它们封装成一个Map,此时collection属性值就是传入的List或array对象在自己封装的map里面的key.

item: 循环体中的具体对象。

index:在list和数组中,index是元素的序号;在map里index 是元素的 key。

open:表示该语句以什么开始。

close:表示该语句以什么结束。

separator:表示在每次进行迭代之间以什么符号作为分隔符。

  • 参数是List集合

参数可以是【arg0或collection或 list】且获取集合个数可以写成size或size(),效果相同

<select id="findProInfoTestForeachList" resultType="com.shpe.chapter3.entity.ProductInfo">
    select * from product_info
    <where>
        <if test="list!=null and list.size>0">
            id in
            <foreach collection="list" open="(" close=")" separator="," item="id">
                #{id}
            </foreach>
        </if>
        <!--  <if test="arg0!=null and arg0.size>0">
              id in
              <foreach collection="arg0" open="(" close=")" separator="," item="id">
                  #{id}
              </foreach>
          </if>-->
          <!--  <if test="collection!=null and collection.size()>0">
               id in
               <foreach collection="collection" open="(" close=")" separator="," item="id">
                   #{id}
               </foreach>
           </if>-->
    </where>
</select>
  • 参数是array数组

参数可以是【array或arg0 】任意一个,效果相同。

<select id="findProInfoTestForeachAyyay" resultType="com.shpe.chapter3.entity.ProductInfo">
    select * from product_info
    <where>
        <!--<if test="arg0!=null and arg0.length>0">
            id in
            <foreach collection="arg0" open="(" close=")" separator="," item="id">
                #{id}
            </foreach>
        </if>-->
        <if test="array!=null and array.length>0">
            id in
            <foreach collection="array" open="(" close=")" separator="," item="id">
                #{id}
            </foreach>
        </if>
    </where>
</select>
  • 参数为Map

参数为Map中对应的Key

<select id="findProInfoTestForeachMap" resultType="com.shpe.chapter3.entity.ProductInfo">
    select * from product_info
    <where>
        <if test="idsKey!=null and idsKey.size>0">
            id in
            <foreach collection="idsKey" open="(" close=")" separator="," item="id">
                #{id}
            </foreach>
        </if>
    </where>
</select>

5.set标签

set标签主要用在更新操作中。

<update id="updateInfo" parameterType="com.shpe.chapter3.entity.ProductInfo">
    UPDATE Product_info
    <set>
        pro_no=#{proNo},pro_name=#{proName}
    </set>
    <where>
        id=#{id}
    </where>
</update>

6.bind标签

bind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。

拿choose、when、otherwise标签的演示案例举例模糊查询

  • 参数为单个参数且为一个对象

_parameter必须是__parameter,不能是其它参数。

<select id="findProInfoTestChoose" parameterType="com.shpe.chapter3.entity.ProductInfo" resultType="com.shpe.chapter3.entity.ProductInfo">
    <bind name="proNo1" value="'%' + _parameter.getProNo() + '%'" />
    select * from product_info
    <where>
        <choose>
            <!--%与#占位符之间必须有空格,不然查不到-->
            <when test="proNo=='1'.toString()">
                and pro_No like #{proNo1}
            </when>
            <when test='proNo=="2"'>
                and pro_No like '%' #{proNo} '%'
            </when>
            <otherwise>
                1=2
            </otherwise>
        </choose>
    </where>
</select>
  • 参数为Map

proNoKey必须是对应绑定对象在Map中的key。

 <select id="findProInfoTestChooseMap" parameterType="map" resultType="com.shpe.chapter3.entity.ProductInfo">
    <bind name="proNo1" value="'%' + proNoKey + '%'" />
    select * from product_info
    <where>
        <choose>
            <!--%与#占位符之间必须有空格,不然查不到-->
            <when test="proNoKey=='1'.toString()">
                and pro_No like #{proNo1}
            </when>
            <when test='proNoKey=="2"'>
                and pro_No like '%' #{proNo} '%'
            </when>
            <otherwise>
                1=2
            </otherwise>
        </choose>
    </where>
</select>
  • 单参数为简单类型(如String)

_parameter可以是任意变量,如命名为aaa或b或c,都可以

<select id="findProInfoTestChooseSinglePram" parameterType="string" resultType="com.shpe.chapter3.entity.ProductInfo">
    <bind name="proNo1" value="'%' + _parameter+ '%'" />
    select * from product_info
    <where>
        <choose>
            <!--%与#占位符之间必须有空格,不然查不到-->
            <when test="proNoKey=='1'.toString()">
                and pro_No like #{proNo1}
            </when>
            <when test='proNoKey=="2"'>
                and pro_No like '%' #{proNo} '%'
            </when>
            <otherwise>
                1=2
            </otherwise>
        </choose>
    </where>
</select>

7.trim标签

trim标签可以看做是一个自定义标签,不常用。常用属性

  • prefix 给sql语句拼接的前缀。
  • suffix 给sql语句拼接的后缀。
  • prefixOverrides 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND"
  • suffixOverrides 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定。
  1. 自定义where

我们改写下,前边where标签的演示案例。

 <select id="findProInfoTestWhere" parameterType="com.shpe.chapter3.entity.ProductInfo" resultType="com.shpe.chapter3.entity.ProductInfo">
     <!-- select * from product_info
      <where>
          <if test="proNo!=null and proNo!=''">
              and pro_No=#{proNo}
          </if>
      </where>-->

      select * from product_info
     <trim prefix="where" prefixOverrides="AND|OR">
         <if test="proNo!=null and proNo!=''">
             and pro_No=#{proNo}
         </if>
     </trim>
</select>
  1. 自定义set
  2. set等价于下列格式,小伙伴可以自己演示下。
<trim prefix="SET" suffixOverrides=",">
...
</trim>

8.script标签

引用官方案例,此处不再列举实例演示。

script要在带注解的映射器接口类中使用动态 SQL,可以使用 script 元素。比如:

    @Update({"<script>",
      "update Author",
      "  <set>",
      "    <if test='username != null'>username=#{username},</if>",
      "    <if test='password != null'>password=#{password},</if>",
      "    <if test='email != null'>email=#{email},</if>",
      "    <if test='bio != null'>bio=#{bio}</if>",
      "  </set>",
      "where id=#{id}",
      "</script>"})
    void updateAuthorValues(Author author);



相关推荐

当Frida来“敲”门(frida是什么)

0x1渗透测试瓶颈目前,碰到越来越多的大客户都会将核心资产业务集中在统一的APP上,或者对自己比较重要的APP,如自己的主业务,办公APP进行加壳,流量加密,投入了很多精力在移动端的防护上。而现在挖...

服务端性能测试实战3-性能测试脚本开发

前言在前面的两篇文章中,我们分别介绍了性能测试的理论知识以及性能测试计划制定,本篇文章将重点介绍性能测试脚本开发。脚本开发将分为两个阶段:阶段一:了解各个接口的入参、出参,使用Python代码模拟前端...

Springboot整合Apache Ftpserver拓展功能及业务讲解(三)

今日分享每天分享技术实战干货,技术在于积累和收藏,希望可以帮助到您,同时也希望获得您的支持和关注。架构开源地址:https://gitee.com/msxyspringboot整合Ftpserver参...

Linux和Windows下:Python Crypto模块安装方式区别

一、Linux环境下:fromCrypto.SignatureimportPKCS1_v1_5如果导包报错:ImportError:Nomodulenamed'Crypt...

Python 3 加密简介(python des加密解密)

Python3的标准库中是没多少用来解决加密的,不过却有用于处理哈希的库。在这里我们会对其进行一个简单的介绍,但重点会放在两个第三方的软件包:PyCrypto和cryptography上,我...

怎样从零开始编译一个魔兽世界开源服务端Windows

第二章:编译和安装我是艾西,上期我们讲述到编译一个魔兽世界开源服务端环境准备,那么今天跟大家聊聊怎么编译和安装我们直接进入正题(上一章没有看到的小伙伴可以点我主页查看)编译服务端:在D盘新建一个文件夹...

附1-Conda部署安装及基本使用(conda安装教程)

Windows环境安装安装介质下载下载地址:https://www.anaconda.com/products/individual安装Anaconda安装时,选择自定义安装,选择自定义安装路径:配置...

如何配置全世界最小的 MySQL 服务器

配置全世界最小的MySQL服务器——如何在一块IntelEdison为控制板上安装一个MySQL服务器。介绍在我最近的一篇博文中,物联网,消息以及MySQL,我展示了如果Partic...

如何使用Github Action来自动化编译PolarDB-PG数据库

随着PolarDB在国产数据库领域荣膺桂冠并持续获得广泛认可,越来越多的学生和技术爱好者开始关注并涉足这款由阿里巴巴集团倾力打造且性能卓越的关系型云原生数据库。有很多同学想要上手尝试,却卡在了编译数据...

面向NDK开发者的Android 7.0变更(ndk android.mk)

订阅Google官方微信公众号:谷歌开发者。与谷歌一起创造未来!受Android平台其他改进的影响,为了方便加载本机代码,AndroidM和N中的动态链接器对编写整洁且跨平台兼容的本机...

信创改造--人大金仓(Kingbase)数据库安装、备份恢复的问题纪要

问题一:在安装KingbaseES时,安装用户对于安装路径需有“读”、“写”、“执行”的权限。在Linux系统中,需要以非root用户执行安装程序,且该用户要有标准的home目录,您可...

OpenSSH 安全漏洞,修补操作一手掌握

1.漏洞概述近日,国家信息安全漏洞库(CNNVD)收到关于OpenSSH安全漏洞(CNNVD-202407-017、CVE-2024-6387)情况的报送。攻击者可以利用该漏洞在无需认证的情况下,通...

Linux:lsof命令详解(linux lsof命令详解)

介绍欢迎来到这篇博客。在这篇博客中,我们将学习Unix/Linux系统上的lsof命令行工具。命令行工具是您使用CLI(命令行界面)而不是GUI(图形用户界面)运行的程序或工具。lsoflsof代表&...

幻隐说固态第一期:固态硬盘接口类别

前排声明所有信息来源于网络收集,如有错误请评论区指出更正。废话不多说,目前固态硬盘接口按速度由慢到快分有这几类:SATA、mSATA、SATAExpress、PCI-E、m.2、u.2。下面我们来...

新品轰炸 影驰SSD多款产品登Computex

分享泡泡网SSD固态硬盘频道6月6日台北电脑展作为全球第二、亚洲最大的3C/IT产业链专业展,吸引了众多IT厂商和全球各地媒体的热烈关注,全球存储新势力—影驰,也积极参与其中,为广大玩家朋友带来了...