MyBatis——动态 SQL

news2024/10/6 8:33:34

一、if 标签

<mapper namespace="com.powernode.mybatis.mapper.CarMapper">
    <select id="selectByMultiCondition" resultType="car">
        select * from t_car where
        <if test="brand != null and brand != ''">
            brand like #{brand}"%"
        </if>
        <if test="guidePrice != null and guidePrice != ''">
            and guide_price >= #{guidePrice}
        </if>
        <if test="carType != null and carType != ''">
            and car_type = #{carType}
        </if>
    </select>
</mapper>

如果第一个条件为空,剩下两个条件不为空,报错,SQL 语法有问题,where 后面出现了 and

解决方案:where 后面添加一个恒成立的条件

此时不管 if 标签是否生效都不会影响 SQL 语句正常执行

<mapper namespace="com.powernode.mybatis.mapper.CarMapper">
    <select id="selectByMultiCondition" resultType="car">
        select * from t_car where 0 = 0
        <if test="brand != null and brand != ''">
            and brand like #{brand}"%"
        </if>
        <if test="guidePrice != null and guidePrice != ''">
            and guide_price >= #{guidePrice}
        </if>
        <if test="carType != null and carType != ''">
            and car_type = #{carType}
        </if>
    </select>
</mapper>

二、where 标签 

where 标签的作用:让 where 子句更加动态智能。

  • 所有条件都为空时,where 标签保证不会生成 where 子句

  • 自动去除某些条件前面多余的 and 或 or(后面多余的 and 不会被去除)

<select id="selectByMultiConditionWithWhere" resultType="car">
  select * from t_car
  <where>
    <if test="brand != null and brand != ''">
      and brand like #{brand}"%"
    </if>
    <if test="guidePrice != null and guidePrice != ''">
      and guide_price >= #{guidePrice}
    </if>
    <if test="carType != null and carType != ''">
      and car_type = #{carType}
    </if>
  </where>
</select>

三、tirm 标签 

trim 标签的属性:

  • prefix:在 trim 标签中的语句前添加内容

  • suffix:在 trim 标签中的语句后添加内容

  • prefixOverrides:前缀覆盖掉(去掉)

  • suffixOverrides:后缀覆盖掉(去掉)

如果所有条件为空,where 不会被加上

<select id="selectByMultiConditionWithTrim" resultType="car">
  select * from t_car
  <trim prefix="where" suffixOverrides="and|or">
    <if test="brand != null and brand != ''">
      brand like #{brand}"%" and
    </if>
    <if test="guidePrice != null and guidePrice != ''">
      guide_price >= #{guidePrice} and
    </if>
    <if test="carType != null and carType != ''">
      car_type = #{carType}
    </if>
  </trim>
</select>

四、set 标签 

主要使用在 update 语句当中,用来生成 set 关键字,同时去掉最后多余的 “,”

比如只更新提交的不为空的字段,如果提交的数据是空或者"",那么这个字段我们将不更新。

<update id="updateWithSet">
  update t_car
  <set>
    <if test="carNum != null and carNum != ''">
        car_num = #{carNum},
    </if>
    <if test="brand != null and brand != ''">
        brand = #{brand},
    </if>
    <if test="guidePrice != null and guidePrice != ''">
        guide_price = #{guidePrice},
    </if>
    <if test="produceTime != null and produceTime != ''">
        produce_time = #{produceTime},
    </if>
    <if test="carType != null and carType != ''">
        car_type = #{carType},
    </if>
  </set>
  where id = #{id}
</update>

五、choose when otherwise

这三个标签是在一起使用的

<choose>
  <when></when>
  <when></when>
  <when></when>
  <otherwise></otherwise>
</choose>

等同于

if(){
    
}else if(){
    
}else if(){
    
}else if(){
    
}else{

}

只有一个分支会被选择!!!!  

六、foreach 标签

循环数组或集合,动态生成 sql,比如这样的 SQL:

delete from t_car where id in(1,2,3);
delete from t_car where id = 1 or id = 2 or id = 3;
insert into t_car values
  (null,'1001','凯美瑞',35.0,'2010-10-11','燃油车'),
  (null,'1002','比亚迪唐',31.0,'2020-11-11','新能源'),
  (null,'1003','比亚迪宋',32.0,'2020-10-11','新能源')

批量删除

  • 使用 in 删除

/**
* 通过foreach完成批量删除
* @param ids
* @return
*/
int deleteBatchByForeach(@Param("ids") Long[] ids);
<!--
	collection:集合或数组
	item:集合或数组中的元素
	separator:分隔符
	open:foreach 标签中所有内容的开始
	close:foreach 标签中所有内容的结束
-->
<delete id="deleteBatchByForeach">
  delete from t_car where id in
  <foreach collection="ids" item="id" separator="," open="(" close=")">
    #{id}
  </foreach>
</delete>
@Test
public void testDeleteBatchByForeach(){
    CarMapper mapper = SqlSessionUtil.openSession().getMapper(CarMapper.class);
    int count = mapper.deleteBatchByForeach(new Long[]{40L, 41L, 42L});
    System.out.println("删除了几条记录:" + count);
    SqlSessionUtil.openSession().commit();
}

  • 使用 or 删除

/**
* 通过foreach完成批量删除
* @param ids
* @return
*/
int deleteBatchByForeach2(@Param("ids") Long[] ids);
<delete id="deleteBatchByForeach2">
  delete from t_car where
  <foreach collection="ids" item="id" separator="or">
    id = #{id}
  </foreach>
</delete>
@Test
public void testDeleteBatchByForeach2(){
    CarMapper mapper = SqlSessionUtil.openSession().getMapper(CarMapper.class);
    int count = mapper.deleteBatchByForeach2(new Long[]{40L, 41L, 42L});
    System.out.println("删除了几条记录:" + count);
    SqlSessionUtil.openSession().commit();
}

批量添加  

/**
* 批量添加,使用foreach标签
* @param cars
* @return
*/
int insertBatchByForeach(@Param("cars") List<Car> cars);
<insert id="insertBatchByForeach">
  insert into t_car values 
  <foreach collection="cars" item="car" separator=",">
    (null,#{car.carNum},#{car.brand},#{car.guidePrice},#{car.produceTime},#{car.carType})
  </foreach>
</insert>
@Test
public void testInsertBatchByForeach(){
    CarMapper mapper = SqlSessionUtil.openSession().getMapper(CarMapper.class);
    Car car1 = new Car(null, "2001", "兰博基尼", 100.0, "1998-10-11", "燃油车");
    Car car2 = new Car(null, "2001", "兰博基尼", 100.0, "1998-10-11", "燃油车");
    Car car3 = new Car(null, "2001", "兰博基尼", 100.0, "1998-10-11", "燃油车");
    List<Car> cars = Arrays.asList(car1, car2, car3);
    int count = mapper.insertBatchByForeach(cars);
    System.out.println("插入了几条记录" + count);
    SqlSessionUtil.openSession().commit();
}

七、sql 标签与 include 标签 

sql 标签用来声明 sql 片段

include 标签用来将声明的 sql 片段包含到某个 sql 语句当中

作用:代码复用、易维护

<sql id="carCols">id,car_num carNum,brand,guide_price guidePrice,produce_time produceTime,car_type carType</sql>

<select id="selectAllRetMap" resultType="map">
  select <include refid="carCols"/> from t_car
</select>

<select id="selectAllRetListMap" resultType="map">
  select <include refid="carCols"/> carType from t_car
</select>

<select id="selectByIdRetMap" resultType="map">
  select <include refid="carCols"/> from t_car where id = #{id}
</select>

一  叶  知  秋,奥  妙  玄  心

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

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

相关文章

ARM架构安全特性之标准安全 API

安全之安全(security)博客目录导读 目录 一、机密计算软件 二、Arm机密计算固件架构 三、认证校验 四、Veraison项目 五、独立于语言的安全API 六、平台抽象安全项目&#xff08;Platform AbstRaction for SECurity project&#xff09; 七、可移植平台安全API 八、…

(undone) 什么是马尔可夫链?Markov Chain

参考视频1&#xff1a;https://www.bilibili.com/video/BV1ko4y1P7Zv/?spm_id_from333.337.search-card.all.click&vd_source7a1a0bc74158c6993c7355c5490fc600 参考视频2&#xff1a;https://www.bilibili.com/video/BV1xg4y1K7z4/?spm_id_from333.788&vd_source7a…

Vue3实战笔记(19)—封装菜单组件

文章目录 前言一、封装左侧菜单导航组件二、使用步骤三、小彩蛋总结 前言 在Vue 3中封装一个左侧导航菜单组件是一项提升项目结构清晰度和代码可复用性的关键任务。这个过程不仅涉及组件的设计与实现&#xff0c;还需考虑其灵活性、易用性以及与Vue 3新特性的紧密结合。以下是…

Golang | Leetcode Golang题解之第88题合并两个有序数组

题目&#xff1a; 题解&#xff1a; func merge(nums1 []int, m int, nums2 []int, n int) {for p1, p2, tail : m-1, n-1, mn-1; p1 > 0 || p2 > 0; tail-- {var cur intif p1 -1 {cur nums2[p2]p2--} else if p2 -1 {cur nums1[p1]p1--} else if nums1[p1] > n…

AXI Interconnect IP核用法

本文描述了如何使用Xilinx的Vivado Design Suite环境中的工具来定制和生成AXI Interconnect IP 核。Vivado Design Suite是一个强大的FPGA设计和开发环境&#xff0c;它允许用户定制和配置各种IP核以适应他们的特定设计需求。 以下是针对如何定制IP核的步骤的简要概述&#xf…

FullCalendar日历组件集成实战(2)

背景 有一些应用系统或应用功能&#xff0c;如日程管理、任务管理需要使用到日历组件。虽然Element Plus也提供了日历组件&#xff0c;但功能比较简单&#xff0c;用来做数据展现勉强可用。但如果需要进行复杂的数据展示&#xff0c;以及互动操作如通过点击添加事件&#xff0…

光数据传送器|光通讯传感器极速版OPT系列尺寸与安装步骤

光数据传送器|光通讯传感器极速版OPT系列是利用可见光及不可见光作为信息载体&#xff0c;无需光纤、网线等有线介质&#xff0c;在空中直接进行信息传输的无线方式通信。驱动光源以可见光及不可见光的高速明暗变化来传输数字信号&#xff0c;以极高光频率双向发射接收光信号&a…

AI与边缘设备,光子芯片,AI规划能力,自然语言驱动的AI游戏

1 Archetype AI 发布了一个创新的人工智能平台 —— Newton 这是一个专门为理解物理世界设计的基础模型。 Newton 设计用于连接实时物理数据&#xff0c;其数据源是全球数十亿传感器的输入&#xff0c;实现了对物理现实的直接解读。 利用从各种传感器&#xff08;如加速度计…

Linux进程间几种通信机制

一. 简介 经过前一篇文章的学习&#xff0c; 我们知道Linux下有两种标准&#xff1a;system V标准和 Posix标准。 System V 和 POSIX 标准是操作系统提供的接口标准&#xff0c;它们规定了操作系统应该如何实现一些基本功能&#xff0c;比如线程、进程间通信、文件处理等。 …

MySQL————创建存储过程函数 有参数传递

存储过程使用大纲 有参数传递 delimiter $$ 声明一个名称为get_student_introduce CREATE PROCEDURE gei_student_introduce(in p_name VARCHAR(20)) 开始操作 BEGIN 撰写真正在操作DMLDQL都行 select introduce 简介 from student WHERE userNamep_name; end $$ delimite…

[muduo网络库]——muduo库TimeStamp类(剖析muduo网络库核心部分、设计思想)

接着之前我们[muduo网络库]——muduo库logger类&#xff08;剖析muduo网络库核心部分、设计思想&#xff09;&#xff0c;我们接下来继续看muduo库中的TimeStamp类&#xff0c;这也是每一个类几乎都能用到的非常简单的类。 TimeStamp类 Timestamp类主要用于日志、定时器模块中…

C语言指针详解(三)

目录 前言 一. 回调函数是什么&#xff1f; 1.定义 2. 代码示例&#xff1a;计数器 2.1 使用回调函数改造前 2.2 使用回调函数改造后 二. qsort使用举例 1. qsort介绍 2. 使用qsort函数排序整型数据 3. 使用qsort排序结构体数据 三. qsort函数的模拟实现 四. sizeo…

单链表经典算法OJ题---力扣21

1.链接&#xff1a;. - 力扣&#xff08;LeetCode&#xff09;【点击即可跳转】 思路&#xff1a;创建新的空链表&#xff0c;遍历原链表。将节点值小的节点拿到新链表中进行尾插操作 遍历的结果只有两种情况&#xff1a;n1为空 或 n2为空 注意&#xff1a;链表为空的情况 代…

[力扣题解] 96. 不同的二叉搜索树

题目&#xff1a;96. 不同的二叉搜索树 思路 动态规划 f[i]&#xff1a;有i个结点有多少种二叉搜索树 状态转移方程&#xff1a; 以n3为例&#xff1a; 以1为头节点&#xff0c;左子树有0个结点&#xff0c;右子树有2个结点&#xff1b; 以2为头节点&#xff0c;左子树有1个…

单文件EXE绿色软件制作工具​Enigma Virtual Box​利用 EnigmaVB 打包 Qt 应用程序

功能描述&#xff1a;详细介绍如何利用 EnigmaVB 打包 Qt 应用程序&#xff0c;从 EnigmaVB 软件下载、安装&#xff0c;到如何使用&#xff0c;一步步教你走进 EnigmaVB 软件&#xff0c;最后还介绍了一款针对 Enigma Virtual Box 制作的单文件程序进行解包的工具 EnigmaVBUnp…

git-将本地项目上传到远程仓库

在gitee中新建一个远程仓库。 填写对应内容。 打开你想上传的文件夹&#xff0c;比如我想上传yuanshen 右击&#xff0c;打开git bash 输入git init初始化仓库 git init 添加项目所有文件 git add . 将添加的文件提交到本地仓库&#xff08;提交说明必填&#xff09; git …

61、内蒙古工业大学、内蒙科学技术研究院:CBAM-CNN用于SSVEP - BCI的分类方法[脑机二区还是好发的]

前言&#xff1a; 之前写过一篇对CBAM模型改进的博客&#xff0c;在CBAM中引入了ECANet结构&#xff0c;对CBAM中的CAM、SAM模块逐一改进&#xff0c;并提出ECA-CBAM单链双链结构&#xff0c;我的这个小的想法已经被一些同学实现了&#xff0c;并进行了有效的验证&#xff0c;…

3.运算符详解(java)

算术运算符 基本四则运算符&#xff1a;加减乘除模&#xff08;、-、*、/、%&#xff09; 注意&#xff1a; 都是二元运算符&#xff0c;使用时必须要有左右两个操作数 int / int 结果还是int类型&#xff0c;而且会向下取整 I.做除法和取模时 右操作数不能为0 II. %不仅可…

福派斯鲜肉狗粮大揭秘,狗狗吃了都说好!

狗粮哪个牌子好&#xff1f;我强烈推荐福派斯鲜肉狗粮&#xff01;在众多狗粮品牌中&#xff0c;福派斯以其高品质、营养均衡以及独特的产品特点&#xff0c;受到了广大宠物主人的一致好评。 (1) 福派斯鲜肉狗粮的配方表透露出其对于原料选择的严谨和用心。高达75%的鲜肉含量&a…

探索美国动态IP池:技术赋能下的网络安全新篇章

在数字化飞速发展的今天&#xff0c;网络安全成为了各行各业关注的焦点。特别是在跨国业务中&#xff0c;如何保障数据的安全传输和合规性成为了企业面临的重要挑战。美国动态IP池作为一种新兴的网络技术&#xff0c;正逐渐走进人们的视野&#xff0c;为网络安全提供新的解决方…