MtBatis学习笔记之动态SQL

文章目录

  • if标签
  • where标签
  • trim标签
  • set标签
  • choose when otherwise
  • 批量删除
  • 批量插入
  • sql标签与include标签

if标签

1、if标签中的test属性是必须的
2、if标签中test属性的值是false或者true
3、如果test是true,则if标签中的sql语句就会拼接,反之,则不会拼接
4、test属性中可以使用的是:
当使用了@Param注解,那么test中要出现的是@Param注解指定的参数名,@Param(“brand”),那么这里只能使用brand
当没有使用@Param注解,那么test中要出现的是:param1,param2,arg0,arg1…
当使用了POJO,那么test中出现的是POJO类的属性名。
5、在mybatis的动态SQL当中,不能使用&&,只能使用and。

//CarMapper.javaList<Car> selectByMultiCondition(@Param("brand")String brand,@Param("guidePrice") Double guidePrice,@Param("carType") String carType);
<!-- CarMapper.xml --><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>
//CarMapperTest.java@Testpublic void testSelectById(){SqlSession sqlSession = SqlSessionUtil.openSession();CarMapper mapper = sqlSession.getMapper(CarMapper.class);List<Car> cars = mapper.selectByMultiCondition("比亚迪",2.0,"新能源");cars.forEach(car -> System.out.println(car));sqlSession.close();}

↑但是上面写的SQL语句明显存在着逻辑的问题,如果第一个判断语句为false,里面的SQL语句没有执行而后面的加上了,就存在SQL语句的语法错误

所以改为下面这种语句

    <select id="selectByMultiCondition" resultType="Car">select * from t_car where 1 = 1<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>

where标签

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

  • 所有条件都为空时,where标签保证不会生成where子句。
  • 自动去除某些条件前面多余的and或or

wher标签是专门负责where子句动态生成的

    <select id="selectByMultiConditionWhere" 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>

trim标签

trim标签的属性

  • prefix:在trim标签中的语句前添加内容
  • suffix:在trim标签中的语句后添加内容
  • prefixOverrides:前缀覆盖掉(去掉)
  • suffixOverrides:后缀覆盖掉(去掉)
    <select id="selectByMultiConditionTrim" 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>
  • prefix="where"是在trim标签所有内容的前面添加where
  • suffixOverrides="and|or"把trim标签中内容的后缀and或or去掉

set标签

主要使用在update语句当中,用来生成set关键字,同时去掉最后多余的“,”
比如我们只更新提交的不为空的字段,如果提交的数据是空,或者“ ”,那么这个字段我们将不更新

int updateWithSet(Car car)
<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>
    @Testpublic void testBySet(){SqlSession sqlSession = SqlSessionUtil.openSession();CarMapper mapper = sqlSession.getMapper(CarMapper.class);Car car = new Car(5L,null,null,"丰田sucker",null,null);mapper.updateWithSet(car);sqlSession.commit();sqlSession.close();}

choose when otherwise

这三个标签是在一起使用的
相当于if、elseif、else
只有一个分支会被选择

    List<Car> selectByChoose(@Param("brand")String brand,@Param("guidePrice")Double guidePrice,@Param("carType")String carType);
    <select id="selectByChoose" resultType="Car">select * from t_car<where><choose><when test="brand != null and brand != ''">brand like "%"#{brand}"%"</when><when test="guidePrice != null and guidePrice != ''">guide_price > #{guidePrice}</when><otherwise>car_type = #{carType}</otherwise></choose></where></select>
    @Testpublic void testchoose(){SqlSession sqlSession = SqlSessionUtil.openSession();CarMapper mapper = sqlSession.getMapper(CarMapper.class);List<Car> cars = mapper.selectByChoose("", 5.0,null);cars.forEach(car -> System.out.println(car));sqlSession.close();}

批量删除

    int deleteByIds(String ids[]);

foreach标签的属性:

  • collection:指定数组或者集合
  • item:代表数组或集合中的元素
  • separator:循环之间的分隔符
    <delete id="deleteByIds">delete from t_car where id in(<foreach collection="ids" item="baga" separator=",">#{baga}</foreach>)</delete>
    @Testpublic void testDelteAll(){SqlSession sqlSession = SqlSessionUtil.openSession();CarMapper mapper = sqlSession.getMapper(CarMapper.class);Long[] ids ={7L, 8L, 9L};int i = mapper.deleteByIds(ids);System.out.println(i);sqlSession.commit();sqlSession.close();}

批量插入

int insertBatch(@Param("cars")List<Car> cars);
    <insert id="insertBatch">insert into t_car values<foreach collection="cars" item="car" separator="," >(null,#{car.carNum},#{car.brand},#{car.guidePrice},#{car.carType},#{car.produceTime})</foreach></insert>
    @Testpublic void testInsertBatch(){SqlSession sqlSession = SqlSessionUtil.openSession();CarMapper mapper = sqlSession.getMapper(CarMapper.class);Car car1 = new Car(null,"八嘎亚路1",30.8,"燃油第",null,"111");Car car2 = new Car(null,"八嘎亚路2",30.8,"燃油第",null,"111");Car car3 = new Car(null,"八嘎亚路3",30.8,"燃油第",null,"111");List<Car> cars = new ArrayList<>();cars.add(car1);cars.add(car2);cars.add(car3);mapper.insertBatch(cars);sqlSession.commit();sqlSession.close();}

sql标签与include标签

sql标签用来声明sql片段
include标签用来将声明的sql片段包含到某个sql语句当中
作用:代码复用,易维护

<sql id="carColumnNameSql">id,car_num as carNum,brnd,guide_price as guidePrice,produce_time as produceTime,car_type as carType
</sql>
<select id="...." resultType="car">select<include refid="carColumnNameSql">from t_car where id = #{id}
</select>

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

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

相关文章

Jenkins从配置到实战(二) - Jenkins如何在多台机器上自动化构建

前言 jenkins除了支持在本机上进行项目构建&#xff0c;还可以将构建任务分发到其他远程服务器上去执行&#xff0c;可以实现在不同平台和架构的机器上来完成项目的自动化构建任务&#xff0c;也能减轻jenkins服务器的压力。本文章就主要介绍下此流程。 准备工作 准备两台机…

Redis—分布式系统

Redis—分布式系统 &#x1f50e;理解分布式&#x1f50e;分布式—应用服务与数据库服务分离引入更多的应用服务节点理解负载均衡 引入更多的数据库服务节点缓存分库分表 微服务 &#x1f50e;常见概念应用(Application) / 系统(System)模块(Module) / 组件(Component)分布式(D…

支持向量机概述

支持向量机在深度学习技术出现之前,使用高斯核的支持向量机在很多分类问题上取得了很好的结果,支持向量机不仅用于分类,还可以用于回归问题。它具有泛化性能好,适合小样本和高维特征的优点。 1. SVM引入 1.1支持向量机分类 支持向量机的基本模型是定义在特征空间上的间隔…

【笔记】markdown易忘速查(对勾/表格/符号/流程图)

https://www.runoob.com/markdown/md-tutorial.html 这里有较系统的免费教程&#xff0c;本篇只是个人的使用备忘录&#xff0c;仅供参考 目录 mark易忘速查目录表格链接符号公式流程/时序/甘特图 mark易忘速查 目录 [toc](目录名称)目录演示 mark易忘速查目录表格链接符号公…

2023年最全OCR技术指南!预训练OCR大模型呼之欲出

OCR是一项科技革新&#xff0c;通过自动化大幅减少人工录入的过程&#xff0c;帮助用户从图像或扫描文档中提取文字&#xff0c;并将这些文字转换为计算机可读格式。这一功能在许多需要进一步处理数据的场景中&#xff0c;如身份验证、费用管理、自动报销、业务办理等都显得尤为…

【Linux】多线程概念理论

目录 1 什么是线程&#xff1f; 2 线程的优点 3 线程的缺点 4 线程异常 5 线程用途 6 Linux线程和进程对比 1 什么是线程&#xff1f; 在一个程序里的一个执行路线就叫做线程&#xff08;thread&#xff09;。更准确的定义是&#xff1a;线程是“一个进程内部的控制序列…

网关与路由器的区别

仅需2分钟&#xff0c;彻底明白网关的工作原理_哔哩哔哩_bilibili网关_百度百科 一、网关的概念 网关(Gateway)又称网间连接器、协议转换器。网关在网络层以上实现网络互连&#xff0c;是复杂的网络互连设备&#xff0c;仅用于两个高层协议不同的网络互连。网关既可以用于广域…

【目标跟踪】1、基础知识

文章目录 一、卡尔曼滤波二、匈牙利匹配 一、卡尔曼滤波 什么是卡尔曼滤波&#xff1f;——状态估计器 卡尔曼滤波用于在包含不确定信息的系统中做出预测&#xff0c;对系统下一步要做什么进行推测&#xff0c;且会结合推测值和观测值来得到修正后的最优值卡尔曼滤波就是利用…

TypeScript基础篇 - Vue-TS-Webpack 环境实战

目录 WebpackVueTS 环境配置 scripts/webpack.config.js src/Hello.tsx src/SfcDemo.vue src/main.tsx src/shims-vue.d.ts package.json WebpackVueTS 环境配置 scripts/webpack.config.js const path require(path) // 安装插件 npm install webpack webpack-cli b…

VS Code 设置大小写转换快捷键

VS Code 设置大小写转换快捷键 前言&#xff1a;VS Code 没有默认的大小写转换快捷键&#xff0c;需要我们自己添加。 一 、打开快捷键设置面板 二、添加快捷键 在搜索框输入 “转换为大写”&#xff0c;如果您的VS Code没有汉化&#xff0c;此处输入“Transform to Uppercase…

SQL中的替换函数replace将字段中的匹配值进行替换

目录 一、更新替换 二、查询替换 一、更新替换 UPDATE 表名 SET 字段名 REPLACE(字段名,匹配值,替换值) WHERE id 1 例&#xff1a;将user表中的address字段中IP1替换为IP2 UPDATE user SET address REPLACE(address,IP1,IP2) 二、查询替换 SELECT *,REPLACE(字段名,…

OSI七层模型和TCP/IP四层模型以及五层模型

OSI七层模型&#xff08;Open System Interconnect&#xff09;即开放系统互连参考模型&#xff0c;是由ISO&#xff08;International Organization for Standardization&#xff09;国际标准化组织提出的&#xff0c;用于计算机或通信系统间互联的标准体系。 从上到下可分为…

【目标跟踪】2、FairMOT | 平衡多目标跟踪中的目标检测和 Re-ID 任务 | IJCV2021

文章目录 一、背景二、方法2.1 Backbone2.2 检测分支2.3 Re-ID 分支2.4 训练 FairMOT2.5 Online Inference 三、效果3.1 数据集3.2 实现细节3.3 消融实验3.4 最终效果 论文&#xff1a;FairMOT: On the Fairness of Detection and Re-Identification in Multiple Object Tracki…

Mybatis单元测试,不使用spring

平时开发过程中需要对mybatis的Mapper类做单元测试&#xff0c;主要是验证语法是否正确&#xff0c;尤其是一些复杂的动态sql&#xff0c;一般项目都集成了spring或springboot&#xff0c;当项比较大时&#xff0c;每次单元测试启动相当慢&#xff0c;可能需要好几分钟&#xf…

[Linux] CentOS7 中 pip3 install 可能出现的 ssl 问题

由于解决问题之后, 才写的博客, 所以没有图片记录. 尽量描述清楚一些 今天写代码的时候, 突然发现 文件里用了#define定义宏之后, coc.nvim的coc-clangd补全就用不了 :checkhealth了一下, 发现nvim忘记支持python3了 尝试pip3 install neovim的时候, 发现会警告然后安装失败.…

linux服务器部署

文章目录 一、基本工具安装1.使用vi命令编辑文件 二、安装1.jdk2.读入数据 总结 一、基本工具安装 1.使用vi命令编辑文件 注:如果vi命令没有&#xff0c;可以使用yum -y install vim或者apt-get install vim命令安装。 Linux操作系统第二讲 二、安装 1.jdk 参考 卸载jdk…

Mybatis-Plus插入数据返回主键两种方式(注解或XML)

废话不多说&#xff0c;直接撸代码: <?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&qu…

递归排序算法快速排序的实现过程

快速排序(Insertion Sort)也是一种递归排序算法。 快速排序原理&#xff1a;先以列表中的任意一个数为基准(一般选头或尾)&#xff0c;将列表分为左、右两个子列表。 左子列表的数要比基准数小&#xff0c;右子列表的数要比基准数大。然后继续把左子列表和右子列表按同样的方…

(2)前端控制器的扩展配置, 视图解析器类型以及MVC执行流程的概述

SpringMVC入门程序的扩展说明 注册前端控制器的细节 在web.xml文件注册SpringMVC的前端控制器DispatcherServlet时使用url-pattern标签中使用/和/*的区别 /可以匹配.html或.js或.css等方式的请求路径,但不匹配*.jsp的请求路径/*可以匹配所有请求(包括.jsp请求), 例如在过滤器…

IDEA导入微服务项目后自动将微服务展示在service面板中

有时候&#xff0c;不会自动将微服务展示在service面板中。 添加service面板&#xff1a; service面板&#xff1a; 更新所有maven&#xff0c;就可以自动将微服务展示在service面板中。