MyBatis使用:动态SQL

news2024/9/24 5:29:46

1、目标

本文的主要目标是使用MyBatis的动态SQL

2、最好使用@Param注解

@Data
public class BaseEntity {

    protected String id;

    protected Integer createUserId;

    protected String createDateTime;

}
@Data
public class News extends BaseEntity {

    private String title;

}
@RestController
@RequiredArgsConstructor
@Log4j2
@RequestMapping("/news")
public class NewsController {

    private final NewsService newsService;

    @PutMapping("/updateByList")
    public String updateByList(@RequestBody News news) {
        newsService.updateByList(news);
        return "updateByList success";
    }

}
@Service
@RequiredArgsConstructor
@Log4j2
public class NewsService {

    private final NewsMapper newsMapper;

    public void updateByList(News news) {
        newsMapper.updateByList(news);
    }
}
@Mapper
public interface NewsMapper {
    void updateByList(@Param("news") News news);
}

每个参数都加上@Param注解

<?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.lwc.mapper.NewsMapper">
    <update id="updateByList">
        update news set title = #{news.title}
        where id = #{news.id}
    </update>
</mapper>

mapper.xml文件中#{}取出News对象的某一个属性,用#{news.属性名字}得到

3、返回值是List集合,resultType写List集合的泛型

@GetMapping("/getNewsList")
public List<News> getNewsList(@RequestParam("title") String title) {
    return newsService.getNewsList(title);
}
public List<News> getNewsList(String title) {
   return newsMapper.getNewsList(title);
}
List<News> getNewsList(@Param("title") String title);

mapper接口的返回值类型是List集合,泛型是News

<select id="getNewsList" resultType="com.lwc.entity.News">
     select id, title, create_user_id createUserId, create_date_time createDateTime from news where title like CONCAT('%', #{title}, '%')
</select>

mapper.xml文件中resultType写List集合的泛型就可以了

4、where标签、if标签、where条件拼接

@GetMapping("/getNewsListByTitleAndUserId")
public List<News> getNewsListByTitleAndUserId(@RequestParam(value = "title", required = false) String title) {
    Integer userId = UserIdThreadLocal.getUserId();
    return newsService.getNewsListByTitleAndUserId(title, userId);
}
public List<News> getNewsListByTitleAndUserId(String title, Integer userId) {
    return newsMapper.getNewsListByTitleAndUserId(title, userId);
}
List<News> getNewsListByTitleAndUserId(@Param("title") String title, @Param("userId") Integer userId);
<select id="getNewsListByTitleAndUserId" resultType="com.lwc.entity.News">
    select id, title, create_user_id createUserId, create_date_time createDateTime from news
    <where>
        <if test="title != null and title != ''">
            and title like CONCAT('%', #{title}, '%')
        </if>
        <if test="userId != null and userId != ''">
            and create_user_id &gt;= #{userId}
        </if>
    </where>
</select>

mapper.xml文件中可以使用where标签、if标签

where的两个查询条件可能都没有,因此不需要加where,所以用where标签

if标签如果test为true就拼接条件,它会自动去除and

字符串拼接用CONCAT函数

大于等于在xml文件可以用&gt;=

大于是&gt;

小于等于是&lt;=

小于是&lt;

测试结果:

在这里插入图片描述

where的两个条件同时满足

在这里插入图片描述

where只有一个条件满足,自动去除and

在这里插入图片描述

where没有条件满足,自动去除where

5、foreach标签遍历

@PutMapping("/updateNewsByIds")
public String updateNewsByIds() {
    newsService.updateNewsByIds();
    return "updateNewsByIds success";
}
public void updateNewsByIds() {
    Map<Map<String, Object>, List<List<String>>> map = new HashMap<>();
    Map<String, Object> tempMap = new HashMap<>();
    tempMap.put("create_user_id", 100);
    tempMap.put("create_date_time", new Date(System.currentTimeMillis()));
    List<String> idList = new ArrayList<>();
    idList.add("a2435411095207fea9f78e8e1d1565bb");
    idList.add("63a95e17fac7b24eabd5b48bbd540c00");
    idList.add("30aa5db26bedaaa308693a80c6fe6116");
    // hutool包可以按照指定大小分割List集合
    List<List<String>> list = ListUtil.partition(idList, 2);
    map.put(tempMap, list);

    tempMap = new HashMap<>();
    tempMap.put("create_user_id", 101);
    tempMap.put("create_date_time", new Date(System.currentTimeMillis()));
    idList = new ArrayList<>();
    idList.add("2aaf3ca4bc6bac9dcf31d3fef655c5b7");
    idList.add("24b4c856aee3deafa5b1b752db0f75ca");
    idList.add("276e60e8a3eb352c5a4c9809c502c0f4");
    // hutool包可以按照指定大小分割List集合
    list = ListUtil.partition(idList, 2);
    map.put(tempMap, list);
    newsMapper.updateNewsByIds(map);
}

id都是Stream流的分组得到的,这里简化了

由于where id in ()这里的参数个数有1000个数的限制,因此需要将这个List集合按照指定的大小分割,hutool包的ListUtil.partition可以进行分割List集合的操作,为了方便检验这里每个List集合分割成只有2个元素

<!--hutool-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.17</version>
</dependency>

这是hutool包的依赖

void updateNewsByIds(@Param("map") Map<Map<String, Object>, List<List<String>>> map);

mapper接口对入参这个map设置@Param(“map”)

<update id="updateNewsByIds">
    <foreach collection="map" index="fieldMap" item="idList" separator=";">
        <foreach collection="idList" item="idSubList" separator=";">
            update news set
            <foreach collection="fieldMap" index="fieldName" item="fieldValue" separator=",">
                ${fieldName} = #{fieldValue}
            </foreach>
            where id in
            <foreach collection="idSubList" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </foreach>
    </foreach>
</update>

mapper.xml文件中用foreach标签对map进行遍历,separator=“;” 表示用分号将多个sql语句分开,open="(“表示遍历开始加上左括号,close=”)"表示遍历结束加上右括号

foreach标签遍历List集合:index是下标,item是List集合指定下标的元素

foreach标签遍历Map:index是map的key,item是map的value

注意:

mysql:允许在单个Statement对象中执行多个SQL语句这种批量操作需要设置allowMultiQueries=true,并且多个SQL语句需要用分号分开

url: jdbc:mysql://ip:port/数据库名字?useUnicode=true&allowMultiQueries=true

oracle:oracle用存储过程,open=“BEGIN” close=“;END;” separator=“;”

测试结果:

在这里插入图片描述

执行多个update操作用分号分开,这里设置的id的最大个数是2

6、update标签可以增加字段或者删除字段

@PutMapping("/addColumn")
public String addColumn(@RequestParam("columnName") String columnName) {
    newsService.addColumn(columnName);
    return "addColumn success";
}
public void addColumn(String columnName) {
    newsMapper.addColumn(columnName);
}
void addColumn(@Param("columnName") String columnName);
<update id="addColumn">
    alter table news add ${columnName} varchar(100)
</update>

7、分页查询

@GetMapping("/getPage")
public List<News> getPage(@RequestParam("size") Integer size, @RequestParam("current") Integer current) {
    return newsService.getPage(size, current);
}
public List<News> getPage(int size, int current) {
    int startRow = (current - 1) * size;
    return newsMapper.getPage(startRow, size);
}
List<News> getPage(@Param("startRow") Integer startRow, @Param("size") Integer size);

对于mysql:

<select id="getPage" resultType="com.lwc.entity.News">
    select id, title, create_user_id createUserId, create_date_time createDateTime from news limit #{startRow}, #{size}
</select>

在这里插入图片描述

对于oracle没有limit,因此用到ROWNUM表示记录的行数

SELECT * FROM (
    SELECT a.*, ROWNUM rnum FROM (
        SELECT * FROM my_table ORDER BY some_column
    ) a
    WHERE ROWNUM <= end_row
) WHERE rnum > start_row;

start_row 是起始行的索引,即 (页码current - 1) * 页大小size

end_row是结束行的索引,即 页码current * 页大小size

优化:

<select id="getPage" resultType="com.lwc.entity.News">
    select id, title, create_user_id createUserId, create_date_time createDateTime from news where id > #{id} order by id desc limit #{size}
</select>

使用主键(通常是 id)进行分页,通过存储最后一条记录的主键来优化查询,而不是使用 OFFSET

在这里插入图片描述

limit xx, size 会扫描前xx个记录,因此会很慢,所以先找到第xx个大的记录的id然后where条件筛选

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

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

相关文章

【C++ Primer Plus习题】5.8

问题: 解答: #include <iostream> #include <cstring> using namespace std;#define SIZE 20int main() {char words[20];char done[] "done";int count 0;while (true){cout << "请输入单词:" << endl;cin >> words;if …

Open3D 最近点约束的体素滤波(35)

Open3D 最近点约束的体素滤波(35) 一、算法介绍二、算法步骤三、具体代码四、实现效果一、算法介绍 最近点约束的体素滤波,是指在每个体素中,选择距离体素中心最近的原始点作为滤波结果,这样保留的是原始点位置。相比于体素滤波的重心点重新计算,或者八叉树体素中心,更加…

进阶岛 茴香豆:企业级知识库问答工具

一、任务介绍 在 InternStudio 中利用 Internlm2-7b 搭建标准版茴香豆知识助手&#xff0c;并使用 Gradio 界面完成 2 轮问答&#xff08;问题不可与教程重复&#xff0c;作业截图需包括 gradio 界面问题和茴香豆回答&#xff09;。知识库可根据根据自己工作、学习或感兴趣的内…

【复旦微FM33 MCU 外设开发指南】外设篇1——GPIO

前言 本系列基于复旦微FM33系列单片机的DataSheet编写&#xff0c;旨在提供一些开发指南。 本文章及本系列其他文章将持续更新&#xff0c;本系列其它文章请跳转【复旦微FM33 MCU 外设开发指南】总集篇 本文章最后更新日期&#xff1a;2024/08/25 文章目录 前言GPIO工作时钟…

PowerShell 一键配置IP

前言 实现一键更改Windows 网卡IP,子网,网关,dns,重命名网卡,获取的接口索引名称,获取接口名称,刷新组策略,刷新系统,脚本可重复配置,,以下环境我是两个网卡配置IP 前提条件 开启wmi,配置网卡,参考 创建更改网卡脚本 实验环境,两个网卡,清除默认,重命名(配置)…

程序员的双重挑战:高效编码与持续学习

在快速变化的编程世界中&#xff0c;程序员们面临着双重挑战&#xff1a;一方面要高效完成日常编码任务&#xff0c;另一方面需要不断学习新技术和深化专业知识&#xff0c;以适应日益复杂的项目需求。如何在这两者之间找到平衡&#xff0c;是许多程序员都感到困惑的问题。本文…

韩国云主机玩游戏性能怎么样

韩国云主机玩游戏性能怎么样&#xff1f;韩国云主机作为高性能的计算服务&#xff0c;为全球游戏玩家提供了一种新的游戏体验方式。用户所关注的韩国云主机在游戏性能方面的表现&#xff0c;可以从多个维度进行详细评估。下面将具体分析韩国云主机用于玩游戏的性能特点&#xf…

卸载通过pip安装的所有Python包的详细指南

卸载所有通过pip安装的Python包的方法总结&#xff08;Windows系统&#xff09; 方法 1: 使用 pip freeze 和 requirements.txt 步骤: 导出依赖到requirements.txt文件: pip freeze > requirements.txt这个命令会将当前环境中所有已安装的Python包及其版本号输出到requirem…

DeepKE-LLM框架介绍及简单使用

简介 DeepKE 作为一个全面的知识提取工具包&#xff0c;不仅在构建知识图谱方面展现出卓越性能&#xff0c;还针对多种场景&#xff08;如cnSchema、低资源环境、文档级处理和多模态分析&#xff09;提供了强大支持。它能高效提取实体、关系和属性&#xff0c;并为初学者提供了…

论文降重,Kimi如何助你一臂之力?

在学术研究的浪潮中&#xff0c;原创性和学术诚信是每位研究者必须坚守的灯塔。然而&#xff0c;随着研究领域的不断扩展和深化&#xff0c;论文写作过程中难免会遇到内容重复的问题&#xff0c;这不仅影响论文的独创性&#xff0c;也对学术声誉构成挑战。本文将介绍Kimi的核心…

幂等方案分析

幂等性介绍 幂等是一个数学上的概念 f(n) 1^ n 无论n为多少 f(n)的值永远为1 在我们的编程中定义为: 无论对某一个资源操作了多少次&#xff0c;其影响都应是相同的。 以SQL为例&#xff1a; select * from table where id1。此SQL无论执行多少次&#xff0c;虽然结果有可…

prometheus入门(简单使用)

架构与组成 先上一张官网的架构图&#xff1a; Prometheus的构成&#xff1a; The Prometheus ecosystem consists of multiple components, many of which are optional: the main Prometheus server which scrapes and stores time series data&#xff08;Prometheus serv…

基本数据类型及命令

String String 是Redis最基本的类型&#xff0c;Redis所有的数据结构都是以唯一的key字符串作为名称&#xff0c;然后通过这个唯一的key值获取相应的value数据。不同的类型的数据结构差异就在于value的结构不同。 String类型是二进制安全的。意思是string可以包含任何数据&…

三大低速总线之SPI

三大低速总线之SPI 文章目录 三大低速总线之SPI前言一、基本概念1.1 物理层1.2 协议1.3 传输过程 二、实战FLASH芯片2.1 SPI-Flash 全擦除实验2.1.1 程序设计 2.2 SPI-Flash 扇区擦除实验2.2.1 整体设计 2.3 SPI-Flash 页写实验2.3.1 操作时序 2.4 SPI_Flash 读数据实验2.4.1 时…

rasterization

在cityfm中有说道 Raster is a rasterization function that maps a closed polygon, represented as an ordered list of nodes, to a binary image 要在Python中实现一个将多边形映射到二值图像的光栅化函数&#xff0c;你可以按照以下步骤进行&#xff1a; 创建一个函数&…

网络安全 day3 --- WAFCDNOSS反向代理正向代理负载均衡

WAF&#xff08;网页防火墙&#xff09; 原理&#xff1a;Web应用防火墙&#xff0c;旨在提供保护 影响&#xff1a;常规Web安全测试手段会受到拦截 实验&#xff1a;Windows2022 IIS D盾 作用是防范网络安全入侵。 如下图&#xff0c;我们在网站目录下放一个简单的一句话木马…

JavaScript初级——文档的加载

1、浏览器在加载一个页面时&#xff0c;是按照自上向下的顺序加载的&#xff0c;读取到一行就运行一行&#xff0c;如果将 script 标签写到页面的上边&#xff0c;在代码运行时&#xff0c;页面还没有加载&#xff0c;页面没有加载DOM对象也没有加载&#xff0c;会导致无法获取…

一个计算勒让德多项式的HTML页面

效果如下 HTML代码 <!DOCTYPE html> <html lang"en"> <head> <meta charset"UTF-8"> <meta name"viewport" content"widthdevice-width, initial-scale1.0"> <title>勒让德多项式</ti…

ZooKeeper体系架构、安装、HA

一、主从架构的单点故障问题 主从架构 Hadoop采用了主从架构&#xff0c;其中包含一个主节点和多个从节点。主节点负责管理整个集群的元数据、任务分配等关键任务&#xff0c;而从节点则负责执行具体的数据存储、计算等操作。 单点故障 在Hadoop主从架构中&#xff0c;主节点作…

Linux并发与竞争

一.概念 Linux 是一个多任务操作系统,肯定会存在多个任务共同操作同一段内存或者设备的情况,多个任务甚至中断都能访问的资源叫做共享资源。在驱动开发中要注意对共享资源的保护,也就是要处理对共享资源的并发访问。 Linux 系统并发产生的原因很复杂,总结一下有下面几个主要原…