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

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

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

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

演示版本为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);



相关推荐

最全的MySQL总结,助你向阿里“开炮”(面试题+笔记+思维图)

前言作为一名编程人员,对MySQL一定不会陌生,尤其是互联网行业,对MySQL的使用是比较多的。对于求职者来说,MySQL又是面试中一定会问到的重点,很多人拥有大厂梦,却因为MySQL败下阵来。实际上...

Redis数据库从入门到精通(redis数据库设计)

目录一、常见的非关系型数据库NOSQL分类二、了解Redis三、Redis的单节点安装教程四、Redis的常用命令1、Help帮助命令2、SET命令3、过期命令4、查找键命令5、操作键命令6、GET命...

netcore 急速接入第三方登录,不看后悔

新年新气象,趁着新年的喜庆,肝了十来天,终于发了第一版,希望大家喜欢。如果有不喜欢看文字的童鞋,可以直接看下面的地址体验一下:https://oauthlogin.net/前言此次带来得这个小项目是...

精选 30 个 C++ 面试题(含解析)(c++面试题和答案汇总)

大家好,我是柠檬哥,专注编程知识分享。欢迎关注@程序员柠檬橙,编程路上不迷路,私信发送以下关键字获取编程资源:发送1024打包下载10个G编程资源学习资料发送001获取阿里大神LeetCode...

Oracle 12c系列(一)|多租户容器数据库

作者杨禹航出品沃趣技术Oracle12.1发布至今已有多年,但国内Oracle12C的用户并不多,随着12.2在去年的发布,选择安装Oracle12c的客户量明显增加,在接下来的几年中,Or...

flutter系列之:UI layout简介(flutter-ui-nice)

简介对于一个前端框架来说,除了各个组件之外,最重要的就是将这些组件进行连接的布局了。布局的英文名叫做layout,就是用来描述如何将组件进行摆放的一个约束。在flutter中,基本上所有的对象都是wi...

Flutter 分页功能表格控件(flutter 列表)

老孟导读:前2天有读者问到是否有带分页功能的表格控件,今天分页功能的表格控件详细解析来来。PaginatedDataTablePaginatedDataTable是一个带分页功能的DataTable,...

Flutter | 使用BottomNavigationBar快速构建底部导航

平时我们在使用app时经常会看到底部导航栏,而在flutter中它的实现也较为简单.需要用到的组件:BottomNavigationBar导航栏的主体BottomNavigationBarI...

Android中的数据库和本地存储在Flutter中是怎样实现的

如何使用SharedPreferences?在Android中,你可以使用SharedPreferencesAPI来存储少量的键值对。在Flutter中,使用Shared_Pref...

Flet,一个Flutter应用的实用Python库!

▼Flet:用Python轻松构建跨平台应用!在纷繁复杂的Python框架中,Flet宛如一缕清风,为开发者带来极致的跨平台应用开发体验。它用最简单的Python代码,帮你实现移动端、桌面端...

flutter系列之:做一个图像滤镜(flutter photo)

简介很多时候,我们需要一些特效功能,比如给图片做个滤镜什么的,如果是h5页面,那么我们可以很容易的通过css滤镜来实现这个功能。那么如果在flutter中,如果要实现这样的滤镜功能应该怎么处理呢?一起...

flutter软件开发笔记20-flutter web开发

flutterweb开发优势比较多,采用统一的语言,就能开发不同类型的软件,在web开发中,特别是后台式软件中,相比传统的html5开发,更高效,有点像c++编程的方式,把web设计出来了。一...

Flutter实战-请求封装(五)之设置抓包Proxy

用了两年的flutter,有了一些心得,不虚头巴脑,只求实战有用,以供学习或使用flutter的小伙伴参考,学习尚浅,如有不正确的地方还望各路大神指正,以免误人子弟,在此拜谢~(原创不易,转发请标注来...

为什么不在 Flutter 中使用全局变量来管理状态

我相信没有人用全局变量来管理Flutter应用程序的状态。毫无疑问,我们的Flutter应用程序需要状态管理包或Flutter的基本小部件(例如InheritedWidget或St...

Flutter 攻略(Dart基本数据类型,变量 整理 2)

代码运行从main方法开始voidmain(){print("hellodart");}变量与常量var声明变量未初始化变量为nullvarc;//未初始化print(c)...