【06】SpringBoot3 MybatisPlus 修改(Mapper)

SpringBoot3 MybatisPlus 修改

  • 前言
  • [修改 API](#修改 API)
    • [update 条件](#update 条件)
    • [update 对象+条件](#update 对象+条件)
    • updateById
    • [updateById 批量(默认)](#updateById 批量(默认))
    • [updateById 批量(自定义)](#updateById 批量(自定义))

前言

本篇中使用到的项目工程是在《SpringBoot3 MybatisPlus 加入日志功能》基础上,持续功能开发。

修改 API

update 条件

无实体参数的 update(Wrapper updateWrapper) 方法,这个方法是默认方法,底层直接调用 update(null, updateWrapper),核心特点是所有更新字段和 where 条件都通过 Wrapper 统一配置,无需传入实体,同时要注意它不支持字段自动填充(比如创建时间、更新时间的自动赋值)。

官网 API:

java 复制代码
    /**
     * 根据 Wrapper 更新记录
     * <p>此方法无法进行自动填充,如需自动填充请使用{@link #update(Object, Wrapper)}</p>
     *
     * @param updateWrapper {@link UpdateWrapper} or {@link LambdaUpdateWrapper}
     * @since 3.5.4
     */
    default int update(@Param(Constants.WRAPPER) Wrapper<T> updateWrapper) {
        return update(null, updateWrapper);
    }

Demo 示例:

java 复制代码
    @Test
    public void testUpdate_02() {
        ClientEntity clientEntity = clientMapper.selectById(301L);
        System.out.println("修改之前:" + JSON.toJSONString(clientEntity));

        UpdateWrapper<ClientEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(ClientEntity::getId, 301L)
                .set(ClientEntity::getNickName, "无实体更新-昵称-测试");

        int update = clientMapper.update(updateWrapper);
        System.out.println("--->>> update = " + update);

        clientEntity = clientMapper.selectById(301L);
        System.out.println("修改之后==>>>clientEntity = " + JSON.toJSONString(clientEntity));

    }

输出日志:

java 复制代码
2026-01-28T22:37:39.009+08:00  INFO 15368 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@187931144 wrapping com.mysql.cj.jdbc.ConnectionImpl@a1cb94] will not be managed by Spring
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 301(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 301, 301, null, null, 更新后-昵称_测试, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2487e20]
修改之前:{"clientId":301,"createdTime":"2026-01-28 22:07:21","id":301,"nickName":"更新后-昵称_测试","upatedTime":"2026-01-28 22:07:21"}
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3395c2a7] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1561688223 wrapping com.mysql.cj.jdbc.ConnectionImpl@a1cb94] will not be managed by Spring
==>  Preparing: UPDATE client SET nick_name=? WHERE (id = ?)
==> Parameters: 无实体更新-昵称-测试(String), 301(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3395c2a7]
--->>> update = 1
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4ebed2b3] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@285646508 wrapping com.mysql.cj.jdbc.ConnectionImpl@a1cb94] will not be managed by Spring
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 301(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 301, 301, null, null, 无实体更新-昵称-测试, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4ebed2b3]
修改之后==>>>clientEntity = {"clientId":301,"createdTime":"2026-01-28 22:07:21","id":301,"nickName":"无实体更新-昵称-测试","upatedTime":"2026-01-28 22:07:21"}

update 对象+条件

官网 API:

java 复制代码
    /**
     * 根据 whereEntity 条件,更新记录
     *
     * @param entity        实体对象 (set 条件值,可以为 null,当entity为null时,无法进行自动填充)
     * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
    

Demo 示例:

java 复制代码
    @Test
    public void testUpdate() {

        ClientEntity clientEntity = new ClientEntity();
        clientEntity.setNickName("更新后-昵称_测试");

        UpdateWrapper<ClientEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", 301L);

        int update = clientMapper.update(clientEntity, updateWrapper);
        System.out.println("update = " + update);

        // 进行查询验证.
        clientEntity = clientMapper.selectById(301L);
        System.out.println("clientEntity = " + JSON.toJSONString(clientEntity));
    }

输出日志:

java 复制代码
2026-01-28T22:27:48.815+08:00  INFO 17412 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1376533963 wrapping com.mysql.cj.jdbc.ConnectionImpl@7791ff50] will not be managed by Spring
==>  Preparing: UPDATE client SET nick_name=? WHERE (id = ?)
==> Parameters: 更新后-昵称_测试(String), 301(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3a70575]
update = 1
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5d74507c] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@800040885 wrapping com.mysql.cj.jdbc.ConnectionImpl@7791ff50] will not be managed by Spring
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 301(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 301, 301, null, null, 更新后-昵称_测试, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5d74507c]
clientEntity = {"clientId":301,"createdTime":"2026-01-28 22:07:21","id":301,"nickName":"更新后-昵称_测试","upatedTime":"2026-01-28 22:07:21"}
2026-01-28T22:27:48.996+08:00  INFO 17412 --- [springboot3-mybatisplus] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...

updateById

官网 API:

java 复制代码
    /**
     * 根据 ID 修改
     *
     * @param entity 实体对象
     */
    int updateById(@Param(Constants.ENTITY) T entity);

Demo 示例:

java 复制代码
    @Test
    public void testUpdate_03() {
        ClientEntity clientEntity = new ClientEntity();
        clientEntity.setId(301L);
        clientEntity.setRealName("根据ID更新-名称");
        int update = clientMapper.updateById(clientEntity);
        System.out.println("update = " + update);

        clientEntity = clientMapper.selectById(301L);
        System.out.println("clientEntity = " + JSON.toJSONString(clientEntity));
    }

输出日志:

java 复制代码
2026-01-28T22:41:24.244+08:00  INFO 13536 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@65194223 wrapping com.mysql.cj.jdbc.ConnectionImpl@362be0cd] will not be managed by Spring
==>  Preparing: UPDATE client SET real_name=? WHERE id=?
==> Parameters: 根据ID更新-名称(String), 301(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@d8e4250]
update = 1
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5b59c3d] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@110044003 wrapping com.mysql.cj.jdbc.ConnectionImpl@362be0cd] will not be managed by Spring
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 301(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 301, 301, null, null, 无实体更新-昵称-测试, 根据ID更新-名称, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5b59c3d]
clientEntity = {"clientId":301,"createdTime":"2026-01-28 22:07:21","id":301,"nickName":"无实体更新-昵称-测试","realName":"根据ID更新-名称","upatedTime":"2026-01-28 22:07:21"}
2026-01-28T22:41:24.417+08:00  INFO 13536 --- [springboot3-mybatisplus] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...

updateById 批量(默认)

参考官网 API 可知默认 1000 条数量批次提交。(int DEFAULT_BATCH_SIZE = 1000;

官网 API:

java 复制代码
    /**
     * 根据ID 批量更新
     *
     * @param entityList 实体对象集合
     * @since 3.5.7
     */
    default List<BatchResult> updateById(Collection<T> entityList) {
        return updateById(entityList, Constants.DEFAULT_BATCH_SIZE);
    }
    /**
     * 默认批次提交数量
     */
    int DEFAULT_BATCH_SIZE = 1000;

updateById 批量(自定义)

官网 API:

java 复制代码
    /**
     * 根据ID 批量更新
     *
     * @param entityList 实体对象集合
     * @param batchSize  插入批次数量
     * @since 3.5.7
     */
    default List<BatchResult> updateById(Collection<T> entityList, int batchSize) {
        MapperProxyMetadata mapperProxyMetadata = MybatisUtils.getMapperProxy(this);
        MybatisBatch.Method<T> method = new MybatisBatch.Method<>(mapperProxyMetadata.getMapperInterface());
        SqlSessionFactory sqlSessionFactory = MybatisUtils.getSqlSessionFactory(mapperProxyMetadata.getSqlSession());
        return MybatisBatchUtils.execute(sqlSessionFactory, entityList, method.updateById(), batchSize);
    }

Demo 示例:

java 复制代码
    @Test
    public void testUpdate_04() {
        // 生成批量测试数据.
        List<ClientEntity> clientEntityList = new ArrayList();
        for(int i = 300; i <= 303; i++) {
            ClientEntity clientEntity = new ClientEntity();
            clientEntity.setId(Long.valueOf(i + 1));
            clientEntity.setClientId(Long.valueOf(i + 1));
            // 此处省略其他属性的 set 方法
            // clientEntity.setXXX;
            clientEntity.setNickName("批量-测试姓名" + i);
            clientEntityList.add(clientEntity);
        }
        // 默认批量提交数量
        int batchSize = 2;
        clientMapper.updateById(clientEntityList, batchSize);

    }

输出日志:

java 复制代码
2026-01-28T22:45:40.694+08:00  INFO 4580 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1878814375 wrapping com.mysql.cj.jdbc.ConnectionImpl@2833c093] will not be managed by Spring
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 301(Long), 批量-测试姓名300(String), 301(Long)
==> Parameters: 302(Long), 批量-测试姓名301(String), 302(Long)
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 303(Long), 批量-测试姓名302(String), 303(Long)

若有转载,请标明出处:https://blog.csdn.net/CharlesYuangc/article/details/157479468

相关推荐
Anastasiozzzz36 分钟前
Java Lambda 揭秘:从匿名内部类到底层原理的深度解析
java·开发语言
骇客野人37 分钟前
通过脚本推送Docker镜像
java·docker·容器
韩立学长1 小时前
基于Springboot泉州旅游攻略平台d5h5zz02(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·旅游
铁蛋AI编程实战1 小时前
通义千问 3.5 Turbo GGUF 量化版本地部署教程:4G 显存即可运行,数据永不泄露
java·人工智能·python
晚霞的不甘1 小时前
CANN 编译器深度解析:UB、L1 与 Global Memory 的协同调度机制
java·后端·spring·架构·音视频
SunnyDays10111 小时前
使用 Java 冻结 Excel 行和列:完整指南
java·冻结excel行和列
摇滚侠1 小时前
在 SpringBoot 项目中,开发工具使用 IDEA,.idea 目录下的文件需要提交吗
java·spring boot·intellij-idea
云姜.1 小时前
java多态
java·开发语言·c++
李堇1 小时前
android滚动列表VerticalRollingTextView
android·java
泉-java2 小时前
第56条:为所有导出的API元素编写文档注释 《Effective Java》
java·开发语言