MyBatis——动态SQL

news2024/9/20 20:50:15

经常遇到很多按照很多查询条件进行查询的情况,比如京东根据不同的条件筛选商品。其中经常出现很多条件不取值的情况,在后台应该如何完成最终的SQL语句呢?

如果采用JDBC进行处理,需要根据条件是否取值进行SQL语句的拼接,一般情况下是使用StringBuilder类及其append方法实现,还是有些繁琐的。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。

MyBatis在简化操作方法提出了动态SQL功能,将使用Java代码拼接SQL语句,改变为在XML映射文件中截止标签拼接SQL语句。相比而言,大大减少了代码量,更灵活、高度可配置、利于后期维护。

MyBatis中动态SQL是编写在mapper.xml中的,其语法和JSTL类似,但是却是基于强大的OGNL表达式实现的。

MyBatis也可以在注解中配置SQL,但是由于注解功能受限,尤其是对于复杂的SQL语句,可读性很差,所以较少使用。

1.if标签

接口

public interface EmpMapper2 {
   List<Emp> findByCondition(Emp emp);
}

SQL语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.msb.mapper.EmpMapper2">

<!--List<Emp> findByCondition(Emp emp);-->
    <select id="findByCondition" resultType="emp">
        select * from emp where 1=1
        <if test="empno != null">
            and empno =#{empno}
        </if>
        <if test="ename != null and ename != ''">
            and ename like concat('%',#{ename},'%')
        </if>
        <if test="job != null and job != ''">
            and job =#{job}
        </if>
        <if test="mgr != null">
            and mgr =#{mgr}
        </if>
        <if test="hiredate != null">
            and hiredate =#{hiredate}
        </if>
        <if test="sal != null">
            and sal =#{sal}
        </if>
        <if test="comm != null">
            and comm =#{comm}
        </if>
        <if test="deptno != null">
            and deptno =#{deptno}
        </if>

    </select>

</mapper>

测试代码

public static void main(String[] args) {
    SqlSession sqlSession = MyBatisUtil.getSqlSession(false);
    EmpMapper2 mapper = sqlSession.getMapper(EmpMapper2.class);
    Emp condition =new Emp();
   /* condition.setDeptno(20);*/
   /* condition.setSal(3000.0);*/
   /*condition.setHiredate(new java.sql.Date(81,1,22));*/
   condition.setComm(0.0);
   condition.setDeptno(20);
    List<Emp> emps = mapper.findEmpByCondition(condition);
    for (Emp e:emps
         ) {
        System.out.println(e);
    }
}

2.where标签

用于处理where关键字和and

<select id="findEmpByCondition" resultType="emp">
    select * from emp
    <where>
        <if test="empno != null">
            and empno= #{empno}
        </if>
        <if test="ename != null and ename != ''">
            and ename= #{ename}
        </if>
        <if test="job != null and job != ''">
            and job= #{job}
        </if>
        <if test="mgr != null ">
            and mgr= #{mgr}
        </if>
        <if test="hiredate != null ">
            and hiredate= #{hiredate}
        </if>
        <if test="sal != null">
            and sal= #{sal}
        </if>
        <if test="comm != null ">
             and comm =#{comm}
        </if>
        <if test="deptno != null ">
            and deptno= #{deptno}
        </if>
    </where>
</select>

Choose标签Choose标签CCCCCCCCCC

3.Choose标签

前面的when条件成立 后面的 when就不再判断了,和where标签的区别

<select id="findEmpByCondition2" resultType="emp">
    select * from emp
    <where>
        <choose>
            <when test="empno != null">
                and empno= #{empno}
            </when>
            <when test="ename != null and ename != ''">
                and ename= #{ename}
            </when>
            <when test="job != null and job != ''">
                and job= #{job}
            </when>
            <when test="mgr != null ">
                and mgr= #{mgr}
            </when>
            <when test="hiredate != null ">
                and hiredate= #{hiredate}
            </when>
            <when test="sal != null">
                and sal= #{sal}
            </when>
            <when test="comm != null ">
                and comm =#{comm}
            </when>
            <when test="deptno != null ">
                and deptno= #{deptno}
            </when>
        </choose>
    </where>
</select>

4.Set标签

接口

int updateEmpByCondtion(Emp emp);

SQL语句

<!--int updateEmpByCondtion(Emp emp);-->
<update id="updateEmpByCondtion" >
    update emp
    <set>
        <if test="ename != null and ename != '' ">
            , ename =#{ename}
        </if>
        <if test="job != null and ename != '' ">
            , job =#{job}
        </if>
        <if test="mgr != null ">
            , mgr =#{mgr}
        </if>
        <if test="hiredate != null ">
            , hiredate =#{hiredate}
        </if>
        <if test="sal != null ">
            , sal =#{sal}
        </if>
        <if test="comm != null ">
            , comm =#{comm}
        </if>
        <if test="deptno != null ">
            , deptno =#{deptno}
        </if>
    </set>
    where empno =#{empno}
</update>

5.Trim标签

Trim 标签处理 set

接口

int updateEmpByCondtion(Emp emp);

SQL语句

<update id="updateEmpByCondition2" >
    update emp
    <!--prefix 要增加什么前缀
    prefixOverrides 要去除什么前缀
    suffix 要增加什么后缀
    suffixOverrides 要去除什么后缀
    set 是trim的一种特殊情况
    -->
    <trim prefix="set"  suffixOverrides="," >
        <if test="ename != null and ename != ''">
            ename= #{ename},
        </if>
        <if test="job != null and job != ''">
            job= #{job},
        </if>
        <if test="mgr != null ">
            mgr= #{mgr},
        </if>
        <if test="hiredate != null ">
            hiredate= #{hiredate},
        </if>
        <if test="sal != null">
            sal= #{sal},
        </if>
        <if test="comm != null ">
            comm =#{comm},
        </if>
        <if test="deptno != null ">
            deptno= #{deptno},
        </if>
    </trim>
    where  empno = #{empno}
</update>

测试代码

Trim标签 处理where

<select id="findEmpByCondition" resultType="emp">
    select * from emp
        <trim prefix="where" prefixOverrides="and">
            <if test="empno != null">
                and empno= #{empno}
            </if>
            <if test="ename != null and ename != ''">
                and ename= #{ename}
            </if>
            <if test="job != null and job != ''">
                and job= #{job}
            </if>
            <if test="mgr != null ">
                and mgr= #{mgr}
            </if>
            <if test="hiredate != null ">
                and hiredate= #{hiredate}
            </if>
            <if test="sal != null">
                and sal= #{sal}
            </if>
            <if test="comm != null ">
                and comm =#{comm}
             </if>
            <if test="deptno != null ">
                and deptno= #{deptno}
            </if>
        </trim>
</select>

6.Bind标签

一般用于处理模糊查询的模板

接口

SQL语句

7.Sql标签

<sql id="empColumn">empno,ename,job,mgr,hiredate,sal,comm,deptno</sql>
<sql id="baseSelect">select <include refid="empColumn"></include> from emp</sql>

<!--List<Emp> findByCondition(Emp emp);-->
<select id="findByCondition" resultType="emp">
    <include refid="baseSelect"></include>
    <trim prefix="where" prefixOverrides="and">
        <if test="empno != null">
            and empno =#{empno}
        </if>
        <if test="ename != null and ename != ''">
            <bind name="likePattern" value="'%'+ename+'%'"/>
            and ename like #{likePattern}
        </if>
        <if test="job != null and job != ''">
            and job =#{job}
        </if>
        <if test="mgr != null">
            and mgr =#{mgr}
        </if>
        <if test="hiredate != null">
            and hiredate =#{hiredate}
        </if>
        <if test="sal != null">
            and sal =#{sal}
        </if>
        <if test="comm != null">
            and comm =#{comm}
        </if>
        <if test="deptno != null">
            and deptno =#{deptno}
        </if>
    </trim>

</select>

8.Foreach标签

接口

SQL语句

<!--List<Emp> findByEmpnos1(int[] empnos);
 collection=""  遍历的集合或者是数组
                 参数是数组,collection中名字指定为array
                 参数是List集合,collection中名字指定为list
 separator=""   多个元素取出的时候 用什么文字分隔
 open=""        以什么开头
 close=""       以什么结尾
 item=""        中间变量名
 for(Person per:PersonList)

 -->
 <select id="findByEmpnos1" resultType="emp">
     select * from emp  where empno in
     <foreach collection="array" separator="," open="(" close=")" item="deptno">
         #{deptno}
     </foreach>
 </select>


<!-- List<Emp> findByEmpnos2(List<Integer> empnos);-->
 <select id="findByEmpnos2" resultType="emp">
     select * from emp  where empno in
     <foreach collection="list" separator="," open="(" close=")" item="deptno">
         #{deptno}
     </foreach>
 </select>

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

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

相关文章

05 缓存预热+缓存雪崩+缓存击穿+缓存穿透

缓存血崩 发生 redis主机挂了&#xff0c;Redis 全盘崩溃比如缓存中有大量数据同时过期 解决 redis缓存集群实现高可用 主从哨兵Redis Cluster ehcache本地缓存 Hystrix或者阿里sentinel限流&降级开启Redis持久化机制aof/rdb&#xff0c;尽快恢复缓存集群 缓存穿透 是…

Gouraud Shading(高洛德着色法)和其优缺点详解

​ Gouraud是一种插值方法&#xff0c;Gouraud着色法是计算机图形学中的一种插值方法&#xff0c;可以为多边形网格表面生成连续的明暗变化。实际使用时&#xff0c;通常先计算三角形每个顶点的光照&#xff0c;再通过双线性插值计算三角形区域中其它像素的颜色。 在图形处理器…

Benewake(北醒) 快速实现TFLuna-IIC与电脑通信的操作说明

目录 1. 概述2. 测试准备2.1 工具准备 3. IIC通讯测试3.1 引脚说明3.2 测试步骤3.2.1 TFLuna-IIC 与 PC 建立连接3.2.2 获取测距值3.2.3 更改 slave 地址 1. 概述 通过本文档的概述&#xff0c;能够让初次使用测试者快速了解测试 IIC 通信协议需要的工具以及查看哪些对应的 II…

小程序容器助力构建新型超级App软件应用架构

所谓软件架构&#xff0c;就是软件系统的骨骼与框架。近年来&#xff0c;软件及开源技术迅猛发展&#xff0c;软件应用架构的概念也愈加普遍。它提供了一种组织和设计软件系统的有效方法&#xff0c;具有许多优势和好处&#xff1a; 模块化和可维护性&#xff1a;软件应用架构将…

Spring Boot 集成Kafka简单应用

说明&#xff1a;当前kafka的版本为2.13-2.8.1&#xff0c;Spring Boot的版本为2.7.6。 第一步&#xff1a;在pom.xml中引入下述依赖 <dependency><groupId>org.springframework.kafka</groupId><artifactId>spring-kafka</artifactId><ver…

Android之解决RecyclerView与NestedScrollView的滑动冲突方法

1、解决RecyclerView与NestedScrollView的滑动冲突 问题一&#xff1a;当我们滑动RecyclerView组件时&#xff0c;上方的轮播图并没有进行滑动&#xff08;NestedScrollView没有滑动&#xff0c;即滑动事件被RecyclerView消费了&#xff09;&#xff0c;当RecyclerView滑到底时…

Nginx的搭建和优化

目录 一. Nginx简介1.1 概述1.2 Nginx和Apache优缺点比较 二. Nginx编译安装步骤1 关闭防火墙&#xff0c;安装依赖包2. 创建运行用户和组3. 编译安装 Nginx4. 做软连接并启动nginx5. 停止Nginx6. 添加nginx系统服务方法一&#xff1a;编写脚本方法二 将nginx命令加入服务 7. 查…

高完整性系统工程(四):Formal Verification and Validation

目录 1. Specification Process 1.1 State Invariants 1.2 Exceptional Behaviour 1.3 Framing 1.4 Summary 2. V&V FOR SPECS 2.1 V&V for formal specs 2.2 Proof 2.3 Proof Assistants 2.4 Model Checking 1. Specification Process Specification Proces…

1128 N Queens Puzzle(21行代码)

分数 20 全屏浏览题目 切换布局 作者 CHEN, Yue 单位 浙江大学 The "eight queens puzzle" is the problem of placing eight chess queens on an 88 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens sha…

QTranslator Class

QTranslator Class QTranslator 类公共成员函数类说明查找翻译使用多种翻译成员函数使用说明 QTranslator 类 QTranslator类为文本输出提供国际化支持。多国语言 Header: #include <QTranslator> qmake: QT core Inherits: QObject公共成员函数 构造函数QTranslator(…

代码随想录算法训练营15期 Day 7 | 454.四数相加II 、 383. 赎金信 、15. 三数之和 、18. 四数之和

昨天看了一下别的东西&#xff0c;导致昨天没有练习打卡&#xff0c;今天补上昨天的学习知识。 454.四数相加II 建议&#xff1a;本题是 使用map 巧妙解决的问题&#xff0c;好好体会一下 哈希法 如何提高程序执行效率&#xff0c;降低时间复杂度&#xff0c;当然使用哈希法 会…

AURIX TC3XX Cached PFLASH与Non-Cached PFLASH的区别

Cached ? Non-Cached&#xff1f; 在阅读TC3XX的用户手册时&#xff0c;在内存映射表中&#xff0c;有两个segment都是Program Flash&#xff0c;而且大小都一样是3M&#xff0c;一个是segment 8 另一个是segment10 这难免让人产生疑惑&#xff0c;二者区别在哪&#xff1f; …

高程实验 二分算法

学校的ppt把相等也考虑到大于上面去了&#xff0c;所以是错误的 1. (程序题) 有n(1<n<1000005)个整数&#xff0c;已经按照从小到大顺序排列好&#xff0c;现在另外给一个整数x&#xff0c;请找出序列中第1个大于x的数的下标&#xff01; 输入&#xff1a; 输入数据包含多…

4. 垃圾收集器ParNewCMS底层三色标记算法详解

JVM性能调优 1. 垃圾收集算法1.1 分代收集理论1.2 标记-复制算法1.3 标记-清除算法1.4 标记-整理算法 2. 垃圾收集器2.1 Serial收集器(-XX:UseSerialGC -XX:UseSerialOldGC)2.2 Parallel Scavenge收集器(-XX:UseParallelGC(年轻代)&#xff0c;-XX:UseParallelOldGC(老年代))2.…

浅谈MySQL主键

常用主键 常用主键 1&#xff09;自增 int、bigint等&#xff0c;顺序递增。 2&#xff09;雪花 雪花算法是因为有时间参数&#xff0c;所以是有序地&#xff0c;而且都是由数字组成。雪花id最大为64位,符合java中long的长度64位&#xff0c;适用于大规模分布式场景。 3&#…

docker基础操作与进阶 - 搭建基于pm2的node环境

1、为什么要使用docker 最近遇到一台机器需要部署两个不同版本node的情况&#xff0c;首先就想起了docker&#xff0c;想必还有其他类似环境问题的情况&#xff0c;需要进行项目隔离&#xff0c;而docker正是用来解决这个问题的。 docker的优势就在于环境隔离&#xff0c;相当…

第九篇、基于Arduino uno,用LCD1602(带IIC的)显示屏显示字符——结果导向

0、结果 说明&#xff1a;可以在LCD1602屏幕上面显示字符&#xff0c;实时的变量&#xff0c;也可以设置是否背光&#xff0c;如果是你想要的&#xff0c;可以接着往下看。 1、外观 说明&#xff1a;注意是带IIC通讯的LCD屏幕&#xff0c;外形如下。 2、连线 说明&#xff…

Hexo写文章不方便?用上GitHub Actions真的是泰裤辣

对于做个人博客的小伙伴来说 HEXO 大家肯定都是非常熟悉的吧,这是一个静态的个人博客程序,通过 HEXO + GitHub Pages 搭建免费个人博客也是很多博主的选择。但相信肯定也会有些困恼,比如博客的渲染维护太麻烦了,我要在一台新设备上写博客并推送到 GitHub Pages 还要先安装 …

【Redis】聊一下哨兵集群

上一篇中&#xff0c;介绍了哨兵机制可以减少主库实例下线的误判率&#xff0c;但是如果只有一个哨兵实例&#xff0c;出现宕机后没有办法保证服务的高可用&#xff0c;所以一般实际的生产环境都是搭建3个哨兵实例构建的集群进行运行。但是具体的运行机制是什么。其实主要就是三…

使用langchain及llama_index实现基于文档(长文本)的相似查询与询问

文章目录 1. 引言2. 简介3. 带关键字的查询方案4. 不带关键字的总结询问5. 实现代码 1. 引言 在调用ChatGPT接口时&#xff0c;我们常常受到4096个字符&#xff08;token&#xff09;的限制。这种限制对于处理长文本或者需要对文档进行相似查询和询问的场景来说是一个挑战。然…