Mybatis:动态SQL(8)

news2024/10/7 15:23:26

动态SQL

  • 1. 动态sql简介
  • 2. if
  • 3. where
  • 4. trim
  • 5. choose、when、otherwise
  • 6. foreach
    • foreach实现批量添加
    • foreach实现批量删除
  • 7. SQL片段
  • 8. 总结

1. 动态sql简介

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了解决拼接SQL语句字符串时的痛点问题

2. if

  • if标签可通过test属性(即传递过来的数据)的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之标签中的内容不会执行
  • 在where后面添加一个恒成立条件1=1
  • 这个恒成立条件并不会影响查询的结果
    • 这个1=1可以用来拼接and语句,例如:当empName为null时
    • 如果不加上恒成立条件,则SQL语句为select * from t_emp where and age = ? and sex = ? and email = ?,此时where会与and连用,SQL语句会报错
    • 如果加上一个恒成立条件,则SQL语句为select * from t_emp where 1= 1 and age = ? and sex = ? and email = ?,此时不报错

DynamicSQLMapper接口

  /**
     * 测试if标签使用,返回Emp的list集合
     * @param emp
     * @return
     */
    public List<Emp> getEmpByConditionOne(Emp emp);

DynamicSQLMapper接口对应的DynamicSQLMapper.xml配置文件

<!--public List<Emp> getEmpByConditionOne(Emp emp);-->
    <select id="getEmpByConditionOne" resultType="Emp">
        select * from t_emp where 1 = 1
        <if test="empName != null and empName != ''">
            and emp_name = #{empName}
        </if>
        <if test="age != null and age != ''">
            and age = #{age}
        </if>
        <if test="sex != null and sex != ''">
            and sex = #{sex}
        </if>
        <if test="email != null and email != ''">
            and email = #{email}
        </if>
    </select>

测试方法

    @Test
    public void testGetEmpByCondition(){
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
        DynamicSQLMapper dynamicSQLMapper = sqlSession.getMapper(DynamicSQLMapper.class);
        Emp emp = new Emp(null, "", 23, "男", "1234@qq.com");
        List<Emp> empList = dynamicSQLMapper.getEmpByConditionOne(emp);
        for(Emp emp1 : empList){
            System.out.println(emp1);
        }
        sqlSession.close();
    }

在这里插入图片描述

3. where

  • where和if一般结合使用:
  • 若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字
  • 若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的and/or去 ,但是不会去掉条件后面多余的and/or

DynamicSQLMapper接口

    /**
     * 测试where标签的使用,返回Emp的List集合
     * @return
     */
    public List<Emp> getEmpByConditionTwo(Emp emp);

DynamicSQLMapper接口对应的DynamicSQLMapper.xml配置文件

 <!--public List<Emp> getEmpByConditionTwo(Emp emp);-->
    <select id="getEmpByConditionTwo" resultType="Emp">
        select * from t_emp
        <where>
            <if test="empName != null and empName != ''">
                and emp_name = #{empName}
            </if>
            <if test="age != null and age != ''">
                and age = #{age}
            </if>
            <if test="sex != null and sex != ''">
                and sex = #{sex}
            </if>
            <if test="email != null and email != ''">
                and email = #{email}
            </if>
        </where>
    </select>

测试方法

    @Test
    public void testGetEmpByConditionTwo(){
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
        DynamicSQLMapper dynamicSQLMapper = sqlSession.getMapper(DynamicSQLMapper.class);
        Emp emp = new Emp(null, "", 235, "", "");
        List<Emp> empList = dynamicSQLMapper.getEmpByConditionTwo(emp);
        System.out.println(empList);
        sqlSession.close();
    }

在这里插入图片描述

4. trim

  • trim用于去掉或添加标签中的内容
  • 常用属性
    • prefix:在trim标签中的内容的前面添加某些内容
    • suffix:在trim标签中的内容的后面添加某些内容
    • prefixOverrides:在trim标签中的内容的前面去掉某些内容
    • suffixOverrides:在trim标签中的内容的后面去掉某些内容
  • 若trim中的标签都不满足条件,则trim标签没有任何效果,也就是只剩下select * from t_emp

DynamicSQLMapper接口

    /**
     * 测试trim标签,返回Emp的List集合
     * @param emp
     * @return
     */
    public List<Emp> getEmpByConditionThree(Emp emp);

DynamicSQLMapper接口对应的DynamicSQLMapper.xml配置文件

<!--  public List<Emp> getEmpByConditionThree(Emp emp);-->
    <select id="getEmpByConditionThree" resultType="Emp">
        select * from t_emp
        <trim prefix="where"  suffixOverrides="and|or">
            <if test="empName != null and empName != ''">
                emp_name = #{empName} and
            </if>
            <if test="age != null and age != ''">
                age = #{age} and
            </if>
            <if test="sex != null and sex != ''">
                sex = #{sex}  and
            </if>
            <if test="email != null and email != ''">
                email = #{email} or
            </if>
        </trim>
    </select>

测试方法

  @Test
    public void testGetEmpByConditionThree(){
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
        DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
        Emp emp = new Emp(null, "", null, "", "1234@qq.com1");
        List<Emp> empList = mapper.getEmpByConditionThree(emp);
        System.out.println(empList);
    }

在这里插入图片描述

5. choose、when、otherwise

  • choose、when、otherwise相当于if...else if..else,(只执行其中最先满足条件的一个)
  • when至少要有一个,otherwise至多只有一个

DynamicSQLMapper接口

    /**
     * 测试choose,when,otherwise标签,
     * @param emp
     * @return
     */
    public List<Emp> getEmpByConditionFour(Emp emp);

DynamicSQLMapper接口对应的DynamicSQLMapper.xml配置文件

<!-- public List<Emp> getEmpByConditionFour(Emp emp);-->
    <select id="getEmpByConditionFour" resultType="Emp">
        select * from t_emp
        <where>
            <choose>
                <when test="empName != null and empName != ''">
                    and emp_name = #{empName}
                </when>
                <when test="age != null and age != ''">
                    and age = #{age}
                </when>
                <when test="sex != null and sex != ''">
                    and sex = #{sex}
                </when>
                <when test="email != null and email != ''">
                    and email = #{email}
                </when>
                <otherwise>
                    and did = 1
                </otherwise>
            </choose>
        </where>
    </select>

测试方法

@Test
    public void testGetEmpByConditionFour(){
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
        DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
        Emp emp = new Emp(null, "yxy", null, "", "");
        List<Emp> empList = mapper.getEmpByConditionFour(emp);
        System.out.println(empList);
        sqlSession.close();
    }

在这里插入图片描述

6. foreach

  • 属性:
  • collection:设置要循环的数组或集合
    • item:表示集合或数组中的每一个数据
    • separator:设置循环体之间的分隔符,分隔符前后默认有一个空格,如,
    • open:设置foreach标签中的内容的开始符
    • close:设置foreach标签中的内容的结束符

foreach实现批量添加

DynamicSQLMapper接口

 /**
     * 使用foreach标签实现批量添加,使用Param注解,规定变量名
     * @param emps
     * @return
     */
    int insertMoreByList(@Param("emps") List<Emp> emps);

DynamicSQLMapper接口对应的DynamicSQLMapper.xml配置文件

<!--int insertMoreByList(@Param("emps")List<Emp> emps);-->
    <insert id="insertMoreByList">
        insert into t_emp values
        <foreach collection="emps" item="emp" separator=",">
            (null, #{emp.empName}, #{emp.age}, #{emp.sex}, #{emp.email}, null)
        </foreach>
    </insert>

测试方法

 @Test
    public void testInsertMoreByList(){
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
        DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
        Emp emp1 = new Emp(null, "a1", 10, "男", "1234@qq.com", null);
        Emp emp2 = new Emp(null, "a2", 10, "男", "1234@qq.com", null);
        Emp emp3 = new Emp(null, "a3", 10, "男", "1234@qq.com", null);
        Emp emp4 = new Emp(null, "a4", 10, "男", "1234@qq.com", null);
        Emp emp5 = new Emp(null, "a5", 10, "男", "1234@qq.com", null);
        Emp emp6 = new Emp(null, "a6", 10, "男", "1234@qq.com", null);

        List<Emp> empList = Arrays.asList(emp1, emp2, emp3, emp4, emp5, emp6);
        int count = mapper.insertMoreByList(empList);
        System.out.println("受影响的行数:" + count);
    }

在这里插入图片描述

foreach实现批量删除

DynamicSQLMapper接口

 /**
     * 使用foreach标签实现批量删除,使用Param注解,规定变量名
     * @param eids
     * @return
     */
    int deleteMoreByArray(@Param("eids") Integer[] eids);

DynamicSQLMapper接口对应的DynamicSQLMapper.xml配置文件

   <!--int deleteMoreByArray(@Param("eids") Integer[] eids);-->
   <!-- delete from t_emp where eid in(id1, id2 id3, ....)-->
    <delete id="deleteMoreByArray">
        delete from t_emp where eid in
        <foreach collection="eids" item="eid" separator="," open="(" close=")">
            #{eid}
        </foreach>
    </delete>

测试方法

    @Test
    public void testDeleteMoreByArray(){
        SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSession();
        DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);
        int result = mapper.deleteMoreByArray(new Integer[]{15, 16, 17, 19, 19});
        System.out.println(result);
        sqlSession.close();
    }

在这里插入图片描述

7. SQL片段

  • sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入
  • 声明sql片段:<sql>标签
<sql id="empColumns">eid,emp_name,age,sex,email</sql>
  • 引用sql片段:<include>标签
    <!--public List<Emp> getEmpAll();-->
    <select id="getEmpAll" resultType="Emp">
        select <include refid="empColumns"/> from t_emp;
    </select>

8. 总结

  1. where和if一般一起使用, where可以自动增加或者删除条件前面的and或者or连接词。
  2. trim是专门用来处理sql连接词问题。
  3. choose、when、otherwise相当于if…else if…else if…else条件判断语句,只有一个能够满足条件
  4. foreach一般用来批量插入数据和删除数据时使用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/80595.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

I-04Python中与C语言STL部分模板的类似模块

C语言中,我们打ACM可以用<vector>、<stack>等模板来快速实现一些经典的数据结构,可我在很多地方都没找到Python中类似于C里面的STL模板这么好用的东西.于是我在Python的标准库里面总结了些模块来直接实现类似的功能(当然也可能是我真的没找到,如果各位来客有知道的…

【浅学Java】SpringMVC程序开发

SpringMVC程序开发1. 认识SpringMVC1.1 SpringMVC是什么1.2 SpringMVC的定义1.3 MVC和SpringMVC的关系经典问题&#xff1a;Spring / SpringBoot / SpringMVC有什区别2. 学习SpringMVC的思路3. Spring MVC的创建和连接3.0 创建方法3.1 使用到的一些注解3.2 返回一个页面3.3 关于…

Qt实现全局鼠标事件监听器-Windows

Qt实现全局鼠标事件监听器-Windows版&#x1f347; 文章目录Qt实现全局鼠标事件监听器-Windows版&#x1f347;1、概述&#x1f348;2、实现效果&#x1f349;3、实现方式&#x1f34a;4、关键代码&#x1f34b;5、源代码&#x1f34c;更多精彩内容&#x1f449;个人内容分类汇…

Quartz任务调度

Quartz概念 Quartz是openSymphony开源组织在Job scheduling领域的开源项目&#xff0c;它可以与J2EE与J2SE应用程序相结合&#xff0c;也可以单独使用。 Quartz是开源且具有丰富特性的“任务调度库”&#xff0c;能够集成于任何的Java应用&#xff0c;小到独立的应用&#xf…

支持向量机SVM

文章目录SVM简单理解SVM代码实现导入数据集SVM实现画出支持向量总结SVM简单理解 在下二维平面存在以下数据点&#xff0c;不同颜色代表不同类别&#xff0c;现在需要画一条直线&#xff0c;想将两个类别分别开来&#xff0c;当有新数据加入时&#xff0c;根据这条直线&#xf…

springboot+jsp母婴用品商城网站系统

开发语言&#xff1a;Java 后端框架&#xff1a;springboot(SpringSpringMVCMyBatis) 前端框架&#xff1a;jsp 数据库&#xff1a;mysql 数据库工具&#xff1a;Navicat11 开发软件&#xff1a;eclipse/myeclipse/idea Maven包&#xff1a;Maven3.3.9 母婴用品网站&#xff0…

客快物流大数据项目(九十六):ClickHouse的VersionedCollapsingMergeTree深入了解

文章目录 ClickHouse的VersionedCollapsingMergeTree深入了解 一、创建VersionedCollapsingMergeTree引擎表的语法 二、折叠数据

人工智能轨道交通行业周刊-第26期(2022.12.5-12.11)

本期关键词&#xff1a;智慧检修、障碍物检测、监管数据平台、ChatGPT、脑机接口、图像增强 1 整理涉及公众号名单 1.1 行业类 RT轨道交通中关村轨道交通产业服务平台人民铁道世界轨道交通资讯网铁路信号技术交流北京铁路轨道交通网上榜铁路视点ITS World轨道交通联盟VSTR铁…

Canvas 性能优化:脏矩形渲染

大家好&#xff0c;我是前端西瓜哥。 使用 Canvas 做图形编辑器时&#xff0c;我们需要自己维护自己的图形树&#xff0c;来保存图形的信息&#xff0c;并定义元素之间的关系。 我们改变画布中的某个图形&#xff0c;去更新画布&#xff0c;最简单的是清空画布&#xff0c;然…

Java项目:SSM个人博客管理系统

作者主页&#xff1a;源码空间站2022 简介&#xff1a;Java领域优质创作者、Java项目、学习资料、技术互助 文末获取源码 项目介绍 管理员角色包含以下功能&#xff1a; 发博客,审核评论,博客增删改查,博客类别增删改查,修改导航,评论增删改查,个人信息修改,登陆页面等功能。 …

TOOD: Task-aligned One-stage Object Detection 原理与代码解析

paper&#xff1a;TOOD: Task-aligned One-stage Object Detection code&#xff1a;https://github.com/fcjian/TOOD 存在的问题 目标检测包括分类和定位两个子任务&#xff0c;分类任务学习的特征主要关注物体的关键或显著区域&#xff0c;而定位任务是为了精确定位整个…

SpringBoot yaml语法详解

SpringBoot yaml语法详解1.yaml基本语法2.yaml给属性赋值3.JSR303校验4.SpringBoot的多环境配置1.yaml基本语法 通常情况下&#xff0c;Spring Boot 在启动时会将 resources 目录下的 application.properties 或 apllication.yaml 作为其默认配置文件&#xff0c;我们可以在该…

【云原生 | Kubernetes 实战】11、K8s 控制器 Deployment 入门到企业实战应用(下)

目录 四、通过 k8s 实现滚动更新 4.3 自定义滚动更新策略 取值范围 建议配置 总结 测试&#xff1a;自定义策略 重建式更新&#xff1a;Recreate 五、生产环境如何实现蓝绿部署&#xff1f; 5.1 什么是蓝绿部署&#xff1f; 5.2 蓝绿部署的优势和缺点 优点&#x…

图数据库 Neo4j 学习之JAVA-API操作

Neo4j 系列 1、图数据库 Neo4j 学习随笔之基础认识 2、图数据库 Neo4j 学习随笔之核心内容 3、图数据库 Neo4j 学习随笔之基础操作 4、图数据库 Neo4j 学习随笔之高级操作 5、图数据库 Neo4j 学习之JAVA-API操作 6、图数据库 Neo4j 学习之SpringBoot整合 文章目录Neo4j 系列前…

mac pro M1(ARM)安装vmware虚拟机及centos8详细教程

前言 mac发布了m1芯片&#xff0c;其强悍的性能收到很多开发者的追捧&#xff0c;但是也因为其架构的更换&#xff0c;导致很多软件或环境的安装成了问题&#xff0c;这次我们接着来看如何在mac m1环境下安装centos8 Centos8安装安装vmware虚拟机Centos8 镜像支持M1芯片安装Cen…

DDPM原理与代码剖析

前言 鸽了好久没更了&#xff0c;主要是刚入学学业压力还蛮大&#xff0c;挺忙的&#xff0c;没时间总结啥东西。 接下来就要好好搞科研啦。先来学习一篇diffusion的经典之作Denoising Diffusion Probabilistic Models(DDPM)。 先不断前向加高斯噪声&#xff0c;这一步骤称为…

论文笔记(二十三):Predictive Sampling: Real-time Behaviour Synthesis with MuJoCo

Predictive Sampling: Real-time Behaviour Synthesis with MuJoCo文章概括摘要1. 介绍2. 背景3. MuJoCo MPC (MJPC)3.1. 物理模拟3.2. 目标3.3. 样条3.4. 规划师4. 结论4.1. 图形用户界面4.2. 例子5. 讨论5.1. 预测抽样5.2. 用例5.3. 局限和未来的工作文章概括 作者&#xff…

25-Vue之ECharts-基本使用

ECharts-基本使用前言ECharts介绍ECharts快速上手ECharts配置说明前言 本篇开始来学习下开源可视化库ECharts ECharts介绍 ECharts是百度公司开源的一个使用 JavaScript 实现的开源可视化库&#xff0c;兼容性强&#xff0c;底层依赖矢量图形 库 ZRender &#xff0c;提供直…

Oracle High Water Mark问题

公司写SQL时遇到一个奇怪的问题&#xff0c;往表中频繁插入和删除大量数据&#xff0c;几次操作后&#xff0c;使用Select查询(表中没数据)特别慢&#xff0c;后得知是高水位线的问题。 该问题已通过: truncate table tableName语句解决。 本想写篇文章详细记录一下的&#xff…

操作系统,计算机网络,数据库刷题笔记9

操作系统&#xff0c;计算机网络&#xff0c;数据库刷题笔记9 2022找工作是学历、能力和运气的超强结合体&#xff0c;遇到寒冬&#xff0c;大厂不招人&#xff0c;可能很多算法学生都得去找开发&#xff0c;测开 测开的话&#xff0c;你就得学数据库&#xff0c;sql&#xff…