iis服务器助手广告广告
返回顶部
首页 > 资讯 > 操作系统 >【MyBatis框架】动态SQL
  • 900
分享到

【MyBatis框架】动态SQL

mybatissqljava数据库mysql 2023-08-30 19:08:47 900人浏览 八月长安
摘要

mybatis之动态sql 目录 MyBatis之动态SQL1. < if > 元素2. < where >3. < choose >,< when >,< otherwise >元素4. < trim >元素5. < s

mybatis之动态sql

开发人员在使用JDBC或者其他类似的框架进行数据库开发时,通常都要根据需求去手动拼装SQL,这是一个非常麻烦且痛苦的工作,而MyBatis提供的对SQL语句动态组装的功能,恰能很好的解决这一麻烦工作。

动态SQL是MyBatis的强大特性之一,其主要元素如下:

元素说明
< if >判断语句,用于条件单分支判断
< choose >相当于Java中的switch语句,用于多分支判断
< where >,< trim >,< set >辅助元素,用于处理一些SQL的拼装,特殊字符等问题
< foreach >循环语句,常用于in语句等列举条件
< bind >用于模糊查询

实体类

public class Emp {    private Integer empId;    private String empName;    private Integer age;    private String gender;      public Emp() {    }     public Emp(Integer empId, String empName, Integer age, String gender) {        this.empId = empId;        this.empName = empName;        this.age = age;        this.gender = gender;    }     public Integer getEmpId() {        return empId;    }     public void setEmpId(Integer empId) {        this.empId = empId;    }     public String getEmpName() {        return empName;    }     public void setEmpName(String empName) {        this.empName = empName;    }     public Integer getAge() {        return age;    }     public void setAge(Integer age) {        this.age = age;    }     public String getGender() {        return gender;    }     public void setGender(String gender) {        this.gender = gender;    }     @Override    public String toString() {        return "Emp{" +                "empId=" + empId +                ", empName='" + empName + '\'' +                ", age=" + age +                ", gender='" + gender + '\'' +                '}';    }}

1. < if > 元素

在MyBatis中,< if > 是最常用的判断语句,它类似于Java中的if语句,主要用于实现某些简单的条件选择

    <select id="getEmpByyCondition" resultType="com.atguigu.mybatis.pojo.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="gender!=null and gender!=''">            and gender=#{gender}        if>    select>

测试方法:

    public void test(){        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();        SqlSession sqlSession = sqlSessionUtils.getSqlSession();        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);        Emp emp = new Emp(null,"张三",null,null);        List<Emp> list = mapper.getEmpByyCondition(emp);        System.out.println(list);    }

测试结果如下:

在这里插入图片描述

同时在为传递任何参数时,程序会将数据表中的所有数据查出

2. < where >

如上述使用if语句查询我们注意到select * from t_emp where 1=1在语句中要添加where 1=1这是为了保证至少有条件成立,不至于程序报错,但是MyBatis的开发者设计了更好的方法,就是把< where >也作为元素,动态添加where,使用如下

 <select id="getEmpByConditionTwo" resultType="Emp">        select * from t_emp        <where>            <if test="empName != null and empName != ''">                emp_name = #{empName}            if>            <if test="age != null and age != ''">                and age = #{age}            if>            <if test="gender != null and gender != ''">                and gender = #{gender}            if>        where>    select>

这样就避免了那个设定

3. < choose >,< when >,< otherwise >元素

在使用< if >元素时,只要test属性中的表达式为true,就会执行元素中的条件语句,但是在实际应用中,有时只需要从多个选项中选择一个去执行。在这种场景下,使用< if > 元素进行处理是非常不合理的。如果使用的是Java语言,这种情况显然更适合switch语句来处理,那么MyBatis中有没有类似的语句呢?当然是有的。针对上面的情况,MyBatsi可以用< choose >,< when >,< otherwise >元素组合去实现上面的情况。

<select id="getEmpByChoose" resultType="Emp">        select * from t_emp        <where>            <choose>                <when test="empName != null and empName != ''">                    emp_name = #{empName}                when>                <when test="age != null and age != ''">                    age = #{age}                when>                <when test="gender != null and gender != ''">                    gender = #{gender}                when>            choose>        where>    select>

测试语句:

public void testGetEmpByChoose(){        SqlSession sqlSession = SqlSessionUtil.getSqlSession();        DynamicSQLMapper mapper = sqlSession.getMapper(DynamicSQLMapper.class);        Emp emp = new Emp(null, "张三", 21, "");        List<Emp> list = mapper.getEmpByChoose(emp);        list.forEach(System.out::println);    }

结果如下:
在这里插入图片描述

这是因为当条件满足其中一项,在这个案例中就是满足了名字,那么后面的就不会再去匹配啦,所以这里的查询是按照名字也就是张三来进行的。

4. < trim >元素

trim元素用于自定义拼接SQL语句,与where类似,具体我们可以对比来看

< where >版

 <select id="getEmpByConditionTwo" resultType="Emp">        select * from t_emp        <where>            <if test="empName != null and empName != ''">                emp_name = #{empName}            if>            <if test="age != null and age != ''">                and age = #{age}            if>            <if test="gender != null and gender != ''">                and gender = #{gender}            if>        where>    select>

< trim >版

<select id="getEmpByCondition" resultType="Emp">        select <include refid="empColumns">include> from t_emp        <trim prefix="where" suffixOverrides="and">            <if test="empName != null and empName != ''">                emp_name = #{empName} and            if>            <if test="age != null and age != ''">                age = #{age} and            if>            <if test="gender != null and gender != ''">                gender = #{gender}            if>        trim>    select>

trim用于去掉或添加标签中的内容

常用属性:

  • prefix:在trim标签中的内容的前面添加某些内容
  • prefixOverrides:在trim标签中的内容的前面去掉某些内容
  • suffix:在trim标签中的内容的后面添加某些内容
  • suffixOverrides:在trim标签中的内容的后面去掉某些内容

5. < set >元素

在更新表中字段时,根据条件进行判断,从而实现部分更改,而不是更新所有字段,提高开发效率

  <update id="updateColumns" parameterType="Emp">        update t_emp         <set>            <if test="empName != null and empName != ''">                emp_name = #{empName} and            if>            <if test="age != null and age != ''">                age = #{age} and            if>            <if test="gender != null and gender != ''">                gender = #{gender}            if>        set>    update>

其中的< if >元素用于判断相应的字段是否传入值,如果传入的字段非空,就将此字段进行动态SQL组转;并更新此字段,否则此字段不更新。

注意:在映射文件中使用 < set > 和 < if >元素组合纪念性update语句动态SQL组转时,如果< set >元素内包含的内容都为空,则会出现SQL语法错误。所以在使用< set > 元素进行字段信息更新时,要确保传入的更新字段都不能为空。

6. < foreach >元素

用于SQL语句执行批量操作

  • collection: 需做foreach(遍历)的对象,作为入参时,list、array对象时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“keyName”)注解来设置自定义collection属性值,设置keyName后,list、array会失效;
  • item: 集合元素迭代时的别名称,该参数为必选项;
  • index: 在list、array中,index为元素的序号索引。但是在Map中,index为遍历元素的key值,该参数为可选项;
  • open: 遍历集合时的开始符号,通常与close=")"搭配使用。使用场景IN(),values()时,该参数为可选项;
  • separator: 元素之间的分隔符,类比在IN()的时候,separator=“,”,最终所有遍历的元素将会以设定的(,)逗号符号隔开,该参数为可选项;
  • close: 遍历集合时的结束符号,通常与open="("搭配使用,该参数为可选项;

6.1 添加批量数据

    <insert id="insertEmps">        insert into t_emp value        <foreach collection="emps" item="emp" separator=",">          (null,#{emp.empName},#{emp.age},#{emp.gender},null)        foreach>    insert>

测试方法:

    public void test(){        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();        SqlSession sqlSession = sqlSessionUtils.getSqlSession();        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);        Emp emp1 = new Emp(null,"数据1",21,"女");        Emp emp2 = new Emp(null,"数据2",24,"男");        Emp emp3 = new Emp(null,"数据3",31,"女");        List<Emp> emps = Arrays.asList(emp1, emp2, emp3);        mapper.insertEmps(emps);    }

执行结果:

在这里插入图片描述

6.2 批量删除数据

    <delete id="deleteByEmpIds">        delete from t_emp where emp_id in        <foreach collection="empIds" item="empId" separator="," open="(" close=")">        #{empId}    foreach>    delete>

测试方法:

    public void test(){        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();        SqlSession sqlSession = sqlSessionUtils.getSqlSession();        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);        Integer empIds[]={6,7};        mapper.deleteByEmpIds(empIds);     }

执行结果:

在这里插入图片描述

也可以这么拼接SQL语句

    <delete id="deleteByEmpIds">        delete from t_emp where        <foreach collection="empIds" item="empId" separator="or" >            emp_id=#{empId}        foreach>    delete>

7. < SQL >元素

sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引用

    <sql id="empColumns"> emp_id,emp_name,age,gendersql>    <select id="selectAll" resultType="com.atguigu.mybatis.pojo.Emp">        select <include refid="empColumns">include> from t_emp    select>

测试方法:

    public void test(){        SqlSessionUtils sqlSessionUtils = new SqlSessionUtils();        SqlSession sqlSession = sqlSessionUtils.getSqlSession();        EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);        List<Emp> emps = mapper.selectAll();        System.out.println(emps);     }

执行结果:

在这里插入图片描述

8. 小结

动态SQL可以帮开发者灵巧的实现很多特殊条件的SQL语句,比如if元素是最常用的,同时要灵活使用sql语句来完成嵌套查询,要根据项目要求选取合适的元素来实现开发。

来源地址:https://blog.csdn.net/m0_64102491/article/details/127477746

--结束END--

本文标题: 【MyBatis框架】动态SQL

本文链接: https://www.lsjlt.com/news/383495.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 【MyBatis框架】动态SQL
    MyBatis之动态SQL 目录 MyBatis之动态SQL1. < if > 元素2. < where >3. < choose >,< when >,< otherwise >元素4. < trim >元素5. < s...
    99+
    2023-08-30
    mybatis sql java 数据库 mysql
  • 第三章 MyBatis框架动态SQL
    第三章 MyBatis框架动态SQL 动态SQL语句是基于OGNL表达式的 通过动态SQL完成多条件查询等逻辑实现 用于实现动态SQL的元素主要有 标签说明 if 条件判断 where 为SQL语句动态添加whe...
    99+
    2018-01-27
    第三章 MyBatis框架动态SQL 数据库入门 数据库基础教程 数据库 mysql
  • MyBatis系列:(5)动态SQL
    1、动态SQL操作之查询查询条件不确定,需要根据情况产生SQL语法,这种情况叫动态SQL    <select id="dynamicFin...
    99+
    2022-10-18
  • MyBatis动态SQL的示例
    这篇文章将为大家详细讲解有关MyBatis动态SQL的示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。动态 SQLMyBatis 的强大特性之一便是它的动态 SQL。如...
    99+
    2022-10-18
  • Fluent MyBatis实现动态SQL
    目录数据准备代码生成在 WHERE 条件中使用动态条件在 UPDATE 使用动态更新choose 标签参考MyBatis 令人喜欢的一大特性就是动态 SQL。在使用 ...
    99+
    2022-11-12
  • mybatis中的动态sql问题
    目录1、if(常用)2、where3、trim4.choose、when、otherwise5、foreach5.1批量删除5.2批量添加6、sql标签总结Mybatis框...
    99+
    2023-02-27
    mybatis动态sql 动态sql mybatis sql
  • MyBatis动态SQL怎么实现
    这篇文章主要介绍了MyBatis动态SQL怎么实现的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇MyBatis动态SQL怎么实现文章都会有所收获,下面我们一起来看看吧。mybatis最强大的功能之一便是它的动态...
    99+
    2023-06-30
  • 如何掌握MyBatis动态SQL
    这篇文章主要介绍“如何掌握MyBatis动态SQL”,在日常操作中,相信很多人在如何掌握MyBatis动态SQL问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何掌握MyBa...
    99+
    2022-10-18
  • MyBatis动态SQL怎么使用
    今天小编给大家分享一下MyBatis动态SQL怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。MyBatis 框架动态...
    99+
    2023-06-29
  • MyBatis 动态SQL全面详解
    目录前言动态sql1.先看一下模块目录结构 2.物理建模和逻辑建模 3. 引入依赖 4.全局配置文件5.sql共性抽取文件 6.mapper接口 if静态sql:动态sql:wher...
    99+
    2022-11-12
  • MyBatis常用动态sql大总结
    简介 相信大家没用Mybatis之前,都碰到过各种条件判断拼接SQL、需要去掉多余的逗号等痛苦,Mybatis中的动态SQL能很好的解决上面说的情况,可以很灵活的组装SQL语句,从...
    99+
    2022-11-12
  • Mybatis动态sql超详细讲解
    目录1、多表关联的嵌套查询2、注解3、动态sql1.if where2.trim3.choose when otherwise4.set5.foreach4、特殊符号处理5...
    99+
    2023-05-17
    mybatis动态sql mybatis 动态sql
  • Mybatis——动态SQL foreach批量操作
    动态SQL Foreach批量操作 前言前置必要知识MySQL批量插入MySQL批量查询MySQL批量修改MySQL批量删除 使用mybatis中的foreach进行批量操作foreach...
    99+
    2023-09-04
    mybatis sql mysql
  • MyBatis中怎么实现动态SQL!
    这篇文章将为大家详细讲解有关MyBatis中怎么实现动态SQL!,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。一、if标签if是最常用标签,经常用在判断语句...
    99+
    2022-10-18
  • Mybatis动态SQL的示例代码
    目录基本流程IF,WhereSetChoose(when,otherwise)SQL片段总结什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句 基本流程 ...
    99+
    2022-11-12
  • MyBatis动态SQL表达式详解
    目录ifchoose when otherwisetrim where setforeachsql片段动态 sql 简单来讲就是我们能通过条件的设置生成不同的 sql,My...
    99+
    2022-12-27
    MyBatis动态SQL MyBatis SQL表达式
  • MyBatis 动态SQL使用及原理
    目录引言1. 动态SQL概述2. if标签3. choose、when和otherwise标签4. trim标签5. set标签和where标签6. foreach7. b...
    99+
    2023-05-20
    MyBatis 动态SQL MyBatis 动态SQL
  • 怎么分析mybatis的动态SQL
    这期内容当中小编将会给大家带来有关怎么分析mybatis的动态SQL,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。1、动态SQL:if 语句根据 username 和 sex 来查询数据。如果userna...
    99+
    2023-06-28
  • Fluent MyBatis怎么实现动态SQL
    这篇文章主要讲解了“Fluent MyBatis怎么实现动态SQL”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Fluent MyBatis怎么实现动态SQL”吧!目录数据准备代码生成在 W...
    99+
    2023-06-20
  • MyBatis 动态SQL之<where>标签-
    简介 where 标签主要用来简化 SQL 语句中的条件判断,可以自动处理 AND/OR 条件。 在if标签和choose-when-otherwise标签的案例中,SQL语句加入了一个条件...
    99+
    2023-09-05
    mybatis java mysql sql 开发语言
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作