JavaWeb 课堂笔记 —— 16 MyBatis 动态SQL

news2025/4/22 4:07:23

本系列为笔者学习JavaWeb的课堂笔记,视频资源为B站黑马程序员出品的《黑马程序员JavaWeb开发教程,实现javaweb企业开发全流程(涵盖Spring+MyBatis+SpringMVC+SpringBoot等)》,章节分布参考视频教程,为同样学习JavaWeb系列课程的同学们提供参考。

01 XML 映射文件

在这里插入图片描述

com/itheima/mapper

EmpMapper.xml

<?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.itheima.mapper.EmpMapper"><!--resultType:单条记录封装的类型-->
    <select id="list" resultType="com.itheima.pojo.Emp"> ⭐⭐
        select * from emp where name like concat('%', '张', '%') and gender = #{gender} and entryDate between #{begin} and #{end} order by update_time desc
    </select>
</mapper>

MybatisX是一款基于IDEA的快速开发MybatisX的插件,用于提高效率。

注:使用Mybatis的注解,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句。

02 动态 SQL

动态SQL为随着用户的输入或外部条件的变化而变化的SQL语句。

在这里插入图片描述

03 if 标签

<if>:通过test属性判断条件是否成立,成立为true,拼接SQL

<where>:在子元素有内容的情况下插入where子句,自动去除子句当中的andor

在这里插入图片描述

EmpMapper.xml

<?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.itheima.mapper.EmpMapper"> 
    <!--resultType:单条记录封装的类型-->
    <select id="list" resultType="com.itheima.pojo.Emp"> ⭐
        select * 
        from emp
        <where>
            <if test="name != null">
                name like concat('%', '张', '%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entryDate between #{begin} and #{end} 
            </if>
        </where>
        order by update_time desc
    </select>
</mapper>

注:and不能简单粗暴的删除,添加<where></where>标签对。

SpringbooyMybatisCrudApplicationTests.java

package com.itheima;

import com.itheima.mapper.EmpMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;
    
    @Test
    public void testList(){
        List<Emp> empList = empMapper.list("张", (short)1, null, null);System.out.println(empList);
    }
}

04 案例:动态更新员工数据信息

需求:动态更新员工信息,如果更新时传递有值,则更新,反之,则不更新。

解决方案:动态SQL

在这里插入图片描述

EmpMapper.xml

<?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.itheima.mapper.EmpMapper"> 
    <update id="update2"> ⭐
    	update emp 
        <set> 
            <if test="username != null">username=#{username},</if>
            <if test="username != null">gender=#{gender},</if>
            <if test="username != null">image=#{image}, </if>
            <if test="username != null">job=#{job}, </if>
            <if test="username != null">entrydate=#{entrydate},</if>
            <if test="username != null">dept_id=#{deptId},</if>
            <if test="username != null">updateTime=#{updateTime}</if>
        </set>
        where id=#{id}
    </update>
</mapper>

注:,不能简单粗暴的删除,添加<set></set>标签对。

SpringbooyMybatisCrudApplicationTests.java

package com.itheima;

import com.itheima.mapper.EmpMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;
    
    @Test
    public void testUpdate(){
        Emp emp = new Emp();
        emp.setId(19); 
        emp.setUsername("Tom222"); 
        emp.setName("汤姆222");
        emp.setGender((short)1);
        emp.setUpdateTime(LocalDateTime.now());
        
        empMapper.update2(emp);}
}

05 foreach 标签

delete from emp where id in(18, 19, 20);

EmpMapper.xml

<?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.itheima.mapper.EmpMapper"> 
    
    <!--批量删除员工 (13, 14, 15)-->
    <delete id="deleteByIds"> ⭐
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete> 
</mapper>

connection:遍历的集合

item:遍历出来的元素

separation:分隔符

open:遍历开始前拼接的SQL片段

close:遍历开始后拼接的SQL片段

SpringbooyMybatisCrudApplicationTests.java

package com.itheima;

import com.itheima.mapper.EmpMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;
    
    @Test
    public void testDeleteByIds(){
        List<Integer> ids = Arrays.asList(13, 14, 15); //构造List集合
        empMapper.deleteByIds(ids);}
}

在这里插入图片描述

在这里插入图片描述

注:不要忘了接口方法哦~

06 sql & include 标签

在这里插入图片描述

EmpMapper.xml

<?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.itheima.mapper.EmpMapper"> 
    <sql id="commonSelect"> ⭐
    	select username, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp
    </sql>
    
    <select id="list" resultType="com.itheima.pojo.Emp">
        <include refid="commonSelect"/> ⭐
        from emp
        <where>
            <if test="name != null">
                name like concat('%', '张', '%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null">
                and entryDate between #{begin} and #{end} 
            </if>
        </where>
        order by undate_time desc
    </select>
</mapper>

<sql>:定义可重用的SQL片段

<include>:通过属性refid,指定包含的SQL片段

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

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

相关文章

Deepseek输出的内容如何直接转化为word文件?

我们有时候会直接利用deepseek翻译别人的文章或者想将deepseek输出的内容直接复制到word文档里。但是文本格式和word是不对应的。这时候需要输入如下命令&#xff1a; 以上翻译内容的格式和排版要求如下&#xff1a; 1、一级标题 字体为黑体&#xff08;三号&#xff09;&…

AI融合SEO关键词实战指南

内容概要 随着人工智能技术的迭代升级&#xff0c;SEO关键词策略正经历从人工经验驱动向数据智能驱动的范式转变。本指南聚焦AI技术在搜索引擎优化中的系统性应用&#xff0c;通过构建多层技术框架实现关键词全生命周期管理。核心方法论涵盖语义分析引擎的构建原理、基于NLP的…

快速入手-基于python和opencv的人脸检测

1、安装库 pip install opencv-python 如果下载比较卡的话&#xff0c;指向国内下载地址&#xff1a; pip3 install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple 2、下载源码 https://opencv.org/ windows11对应的版本下载&#xff1a; https://pan.baidu…

汽车免拆诊断案例 | 2011款雪铁龙世嘉车刮水器偶尔自动工作

故障现象 一辆2011款雪铁龙世嘉车&#xff0c;搭载1.6 L 发动机&#xff0c;累计行驶里程约为19.8万km。车主反映&#xff0c;该车刮水器偶尔会自动工作&#xff0c;且前照灯偶尔会自动点亮。 故障诊断 接车后试车发现&#xff0c;除了上述故障现象以外&#xff0c;当用遥控器…

8.QT-按钮类控件|Push Button|Radio Button|Check Box|Tool Button(C++)

Push Button 使⽤ QPushButton 表⽰⼀个按钮.这也是当前我们最熟悉的⼀个控件了. QPushButton 继承⾃ QAbstractButton .这个类是⼀个抽象类.是其他按钮的⽗类 在Qt Designer中也能够看到这⾥的继承关系 属性说明text按钮中的⽂本icon按钮中的图标iconSize按钮中图标的尺⼨sh…

STM32嵌入式

一、创建工程项目 1、进入软件首页 2、新建项目,【file】->【new project】 3、选择需要的芯片 4、系统内核部分设置 ① 选择晶振&#xff08;使用外部的高速晶振&#xff09; ② 选择debug形式&#xff08;SW类型&#xff09; 5、时钟设置 6、选择自己需要的引脚设置&a…

Transformer系列(一):NLP中放弃使用循环神经网络架构

NLP中放弃使用循环神经网络架构 一、符号表示与概念基础二、循环神经网络1. 依赖序列索引存在的并行计算问题2. 线性交互距离 三、总结 该系列笔记阐述了自然语言处理&#xff08;NLP&#xff09;中不再采用循环架构&#xff08;recurrent architectures&#xff09;的原因&…

9.QT-显示类控件|Label|显示不同格式的文本|显示图片|文本对齐|自动换行|缩进|边距|设置伙伴(C++)

Label QLabel 可以⽤来显⽰⽂本和图⽚ 属性说明textQLabel中的⽂本textFormat⽂本的格式.• Qt::PlainText 纯⽂本• Qt::RichText 富⽂本(⽀持html标签)• Qt::MarkdownText markdown格式• Qt::AutoText 根据⽂本内容⾃动决定⽂本格式pixmapQLabel 内部包含的图⽚.scaledCo…

【c语言】深入理解指针1

深入理解指针1 一、数组名的理解二、使用指针访问数组三、一维数组传参本质四、二级指针 一、数组名的理解 数组名就是数组首元素的地址&#xff0c;类型是指针类型&#xff0c;但是存在两个例外&#xff1a; sizeof(arr) : 整个数组在内存中的大小 &arr : 整个数组的地址…

4.QT-信号和槽|存在意义|信号和槽的连接方式|信号和槽断开|lambda表达式|信号和槽优缺点(C++)

信号和槽存在意义 所谓的信号槽&#xff0c;终究要解决的问题&#xff0c;就是响应用户的操作 信号槽&#xff0c;其实在GUI开发的各种框架中&#xff0c;是一个比较有特色的存在 其他的GUI开发框架&#xff0c;搞的方式都要更简洁一些&#xff5e;~ 网页开发 (js dom api) 网…

单元测试的一般步骤

Qt Test Qt Test 是 Qt 开发人员发布的一个单元测试框架&#xff0c;用于测试基于 Qt 框架的应用程序或库。它提供了单元测试框架中常见的所有功能以及用于测试图形用户界面的扩展。 1.自动化测试包络ui测试>接口测试>单元测试&#xff1b;现问如何使用Qt进行单元测试&…

UE5 渲染视频

文章目录 概述插件开始渲染渲染透明背景的视频 概述 渲染视频需要使用关卡序列 渲染原理就是将一个关卡序列渲染为序列帧 序列帧放到AE里会自动变成视频 UE版本是5.4.4 插件 首先开启新的渲染插件&#xff0c;否则会自动使用旧的渲染插件 插件里搜Render&#xff0c;开启这…

pycharm无法识别到本地python的conda环境解决方法

问题一 现象描述&#xff1a; 本地已经安装了conda&#xff0c;但在pycharm中选择conda环境却识别不到&#xff0c; 解决方法&#xff1a;手动输入conda path&#xff0c;点击R eload environments基本就能修复&#xff0c;比如我的路径如下 /Users/test/conda/miniconda3/b…

LFM调制信号分类与检测识别

LFM调制信号分类与检测识别 LFM调制信号分类识别AlexNet网络识别InceptionV3、ResNet-18、ResNet-50网络识别 LFM调制信号检测识别 LFM调制信号分类识别 支持识别LFM信号、间歇采样干扰(ISRJ)、灵巧噪声干扰(SNJ)、扫频干扰(SJ)、瞄准干扰(AJ)、阻塞干扰(BJ)、密集假目标干扰(…

头歌实训之连接查询

&#x1f31f; 各位看官好&#xff0c;我是maomi_9526&#xff01; &#x1f30d; 种一棵树最好是十年前&#xff0c;其次是现在&#xff01; &#x1f680; 今天来学习C语言的相关知识。 &#x1f44d; 如果觉得这篇文章有帮助&#xff0c;欢迎您一键三连&#xff0c;分享给更…

常见的服务器硬盘接口

常见的服务器硬盘接口有SATA、SAS、M.2、U.2 一、SATA接口 SATA&#xff08;Serial Advanced Technology Attachment&#xff09;是广泛应用于存储设备的串行接口标准&#xff0c;在服务器中主要用于连接大容量机械硬盘&#xff08;HDD&#xff09;或经济型固态硬盘&#xff…

SpringBoot编写单元测试

pom.xml引入单元测试的坐标 <!--单元测试坐标--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>编写单元测试类 测试类…

目标分割模型优化自身参数都是梯度下降算法吗?

在计算机视觉的深度学习任务中&#xff0c;诸如 CNN、FCN、U-Net、DeepLab 系列模型已成为图像分类与图像分割任务的核心架构。它们在网络结构和任务上有所差异&#xff0c;但是否共享同一种优化机制&#xff1f;是否都使用梯度下降&#xff1f;优化过程中又有什么本质区别&…

基于springboot的商城

1 项目使用技术 后端框架&#xff1a;SpringBoot 数据库&#xff1a;MySQL 开发工具&#xff1a;IDEA 2 项目功能模块 商城功能包含前台和后台。 &#xff08;1&#xff09;前台主要包含&#xff1a;用户注册登录模块、首页模块、搜索模块、商品详情、购物车、提交订单、…

MATLAB 控制系统设计与仿真 - 37

范数鲁棒控制器的设计 鲁棒控制器的设计 根据双端子状态方程对象模型结构&#xff0c;控制器设计的目标是找到一个控制器K(s),它能保证闭环系统的范数限制在一个给定的小整数下&#xff0c;即 这时控制器的状态方程为&#xff1a; 其中X与Y分别为下面两个代数Riccati方程的解…