【05】SpringBoot3 MybatisPlus 添加(Mapper)

SpringBoot3 MybatisPlus 添加(Mapper)

  • 前言
  • [添加 API](#添加 API)
    • insert
    • [insert 批量(默认)](#insert 批量(默认))
    • [insert 批量(自定义)](#insert 批量(自定义))
    • insertOrUpdate
    • [insertOrUpdate 批量(默认)](#insertOrUpdate 批量(默认))
    • [insertOrUpdate 批量(自定义)](#insertOrUpdate 批量(自定义))

前言

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

添加 API

insert

官网 API:

java 复制代码
    /**
     * 插入一条记录
     *
     * @param entity 实体对象
     */
    int insert(T entity);

Demo 示例:

java 复制代码
    @Test
    public void testInsert() {
        ClientEntity clientEntity = new ClientEntity();
        clientEntity.setId(999L);
        clientEntity.setClientId(1001L);
        // 此处省略其他属性的 set 方法
        // clientEntity.setXXX;
        clientEntity.setNickName("测试姓名999");
        int insertResult = clientMapper.insert(clientEntity);
        System.out.println("insertResult = " + insertResult);
    }

输出日志:

insert 批量(默认)

查阅官网 API 可知,默认 int DEFAULT_BATCH_SIZE = 1000; 按 1000 条数据进行批量提交。

官网 API:

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

Demo 示例:

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

        // 生成批量测试数据.
        List<ClientEntity> clientEntityList = new ArrayList();
        for(int i = 200; i <= 210; 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);
        }

        // 批量添加.
        List<BatchResult> batchResults = clientMapper.insert(clientEntityList);
        System.out.println("batchResults = " + batchResults);

    }
    

输出日志:

insert 批量(自定义)

查看官网 API ,支持自定义批量提交的数量参数。

官网 API:

java 复制代码
    /**
     * 插入(批量)
     *
     * @param entityList 实体对象集合
     * @param batchSize  插入批次数量
     * @since 3.5.7
     */
    default List<BatchResult> insert(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.insert(), batchSize);
    }

Demo 示例:

java 复制代码
    @Test
    public void testInsert_03() {
        // 生成批量测试数据.
        List<ClientEntity> clientEntityList = new ArrayList();
        for(int i = 300; i < 310; 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 = 5;
        List<BatchResult> batchResults = clientMapper.insert(clientEntityList, batchSize);
        System.out.println("batchResults = " + batchResults);

    }
    

输出日志:

insertOrUpdate

如果待添加的数据,在数据库中已经存在,则进行 更新(update),反之 进行 添加(insert)

官网 API

java 复制代码
    /**
     * 主键存在更新记录,否插入一条记录
     *
     * @param entity 实体对象 (不能为空)
     * @since 3.5.7
     */
    default boolean insertOrUpdate(T entity) {
        Class<?> entityClass = ReflectionKit.getSuperClassGenericType(getClass(), BaseMapper.class, 0);
        Assert.notNull(entityClass, "entityClass must not be null");
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
        Assert.notNull(tableInfo, "Can not get TableInfo for entity " + entityClass);
        String keyProperty = tableInfo.getKeyProperty();
        Assert.notEmpty(keyProperty, "The current table has no primary key.");
        Object idVal = tableInfo.getPropertyValue(entity, keyProperty);
        return StringUtils.checkValNull(idVal) || Objects.isNull(selectById((Serializable) idVal)) ? insert(entity) > 0 : updateById(entity) > 0;
    }

Demo 示例:

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

        // 测试已经存在的数据,是否更新?
        // 301(Long), 301(Long), 测试姓名300(String)
        ClientEntity clientEntity1 = new ClientEntity();
        clientEntity1.setId(301L);
        clientEntity1.setClientId(301L);
        clientEntity1.setNickName("君九");
        clientMapper.insertOrUpdate(clientEntity1);

        // 测试未存在的数据,是否添加?
        ClientEntity clientEntity2 = new ClientEntity();
        clientEntity2.setId(9301L);
        clientEntity2.setClientId(9301L);
        clientEntity2.setNickName("新增姓名:君九");
        clientMapper.insertOrUpdate(clientEntity2);

        // 查询数据,进行验证
        List<ClientEntity> clientEntityList = clientMapper.selectList(
                new QueryWrapper<ClientEntity>().lambda().like(ClientEntity::getNickName, "君九")
        );
        System.out.println("clientEntityList 个数 = " + clientEntityList.size());
        System.out.println(JSON.toJSONString(clientEntityList));

    }
    

输出日志:

java 复制代码
2026-01-28T22:07:35.796+08:00  INFO 13720 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@948208151 wrapping com.mysql.cj.jdbc.ConnectionImpl@1dcca426] 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, 测试姓名300, 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@704c3bdf]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3b347439] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@681200528 wrapping com.mysql.cj.jdbc.ConnectionImpl@1dcca426] will not be managed by Spring
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 301(Long), 君九(String), 301(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3b347439]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5f68eec6] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1341781781 wrapping com.mysql.cj.jdbc.ConnectionImpl@1dcca426] 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: 9301(Long)
<==      Total: 0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5f68eec6]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6cb194f5] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@814507488 wrapping com.mysql.cj.jdbc.ConnectionImpl@1dcca426] will not be managed by Spring
==>  Preparing: INSERT INTO client ( id, client_id, nick_name ) VALUES ( ?, ?, ? )
==> Parameters: 9301(Long), 9301(Long), 新增姓名:君九(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6cb194f5]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@47d9c01] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@649913869 wrapping com.mysql.cj.jdbc.ConnectionImpl@1dcca426] 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 (nick_name LIKE ?)
==> Parameters: %君九%(String)
<==    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
<==        Row: 9301, 9301, null, null, 新增姓名:君九, null, 2026-01-28 22:07:35, 2026-01-28 22:07:35
<==      Total: 2
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@47d9c01]
clientEntityList 个数 = 2
[{"clientId":301,"createdTime":"2026-01-28 22:07:21","id":301,"nickName":"君九","upatedTime":"2026-01-28 22:07:21"},{"clientId":9301,"createdTime":"2026-01-28 22:07:35","id":9301,"nickName":"新增姓名:君九","upatedTime":"2026-01-28 22:07:35"}]
2026-01-28T22:07:36.062+08:00  INFO 13720 --- [springboot3-mybatisplus] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2026-01-28T22:07:36.069+08:00  INFO 13720 --- [springboot3-mybatisplus] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

insertOrUpdate 批量(默认)

官网 API:

java 复制代码
    /**
     * 批量修改或插入
     *
     * @param entityList 实体对象集合
     * @since 3.5.7
     */
    default List<BatchResult> insertOrUpdate(Collection<T> entityList) {
        return insertOrUpdate(entityList, Constants.DEFAULT_BATCH_SIZE);
    }

Demo 示例:

java 复制代码
    @Test
    public void testInsertOrUpdate_02() {
        // 生成批量测试数据.
        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);
        }
        clientMapper.insertOrUpdate(clientEntityList);
    }

输出日志:

java 复制代码
2026-01-28T22:12:13.764+08:00  INFO 12712 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1360879214 wrapping com.mysql.cj.jdbc.ConnectionImpl@b339a08] 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
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 301(Long), 测试姓名300(String), 301(Long)
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 302(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 302, 302, null, null, 测试姓名301, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 302(Long), 测试姓名301(String), 302(Long)
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 303(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 303, 303, null, null, 测试姓名302, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 303(Long), 测试姓名302(String), 303(Long)
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 304(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 304, 304, null, null, 测试姓名303, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 304(Long), 测试姓名303(String), 304(Long)
2026-01-28T22:12:13.881+08:00  INFO 12712 --- [springboot3-mybatisplus] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...

insertOrUpdate 批量(自定义)

官网 API:

java 复制代码
    /**
     * 批量修改或插入
     *
     * @param entityList 实体对象集合
     * @param batchSize  插入批次数量
     * @since 3.5.7
     */
    default List<BatchResult> insertOrUpdate(Collection<T> entityList, int batchSize) {
        MapperProxyMetadata mapperProxyMetadata = MybatisUtils.getMapperProxy(this);
        Class<?> entityClass = ReflectionKit.getSuperClassGenericType(getClass(), BaseMapper.class, 0);
        Assert.notNull(entityClass, "entityClass must not be null");
        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
        Assert.notNull(tableInfo, "Can not get TableInfo for entity " + entityClass);
        String keyProperty = tableInfo.getKeyProperty();
        Assert.notEmpty(keyProperty, "The current table has no primary key.");
        String statement = mapperProxyMetadata.getMapperInterface().getName() + StringPool.DOT + SqlMethod.SELECT_BY_ID.getMethod();
        return insertOrUpdate(entityList, (sqlSession, entity) -> {
            Object idVal = tableInfo.getPropertyValue(entity, keyProperty);
            return StringUtils.checkValNull(idVal) || CollectionUtils.isEmpty(sqlSession.selectList(statement, entity));
        }, batchSize);
    }

Demo 示例:

java 复制代码
    @Test
    public void testInsertOrUpdate_03() {
        // 生成批量测试数据.
        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.insertOrUpdate(clientEntityList, batchSize);
    }

输出日志:

java 复制代码
2026-01-28T22:15:10.891+08:00  INFO 16016 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1946338463 wrapping com.mysql.cj.jdbc.ConnectionImpl@6ceb11f9] 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, 测试姓名300, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 301(Long), 测试姓名300(String), 301(Long)
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 302(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 302, 302, null, null, 测试姓名301, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 302(Long), 测试姓名301(String), 302(Long)
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 303(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 303, 303, null, null, 测试姓名302, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 303(Long), 测试姓名302(String), 303(Long)
==>  Preparing: SELECT id,client_id,user_no,user_password,nick_name,real_name,created_time,upated_time FROM client WHERE id=?
==> Parameters: 304(Long)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 304, 304, null, null, 测试姓名303, null, 2026-01-28 22:07:21, 2026-01-28 22:07:21
<==      Total: 1
==>  Preparing: UPDATE client SET client_id=?, nick_name=? WHERE id=?
==> Parameters: 304(Long), 测试姓名303(String), 304(Long)
2026-01-28T22:15:11.012+08:00  INFO 16016 --- [springboot3-mybatisplus] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...

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

相关推荐
.Peter3 小时前
.NET/WPF 程序在部分 Windows 电脑无法保存用户环境变量:使用 DPAPI 实现安全兼容
windows·信息安全·c#·.net·wpf·环境变量·dpapi
码字的特恩4 小时前
微软确认暂不为 Windows 11 加入透明效果自定义功能,建议用户使用第三方工具
人工智能·windows·算法·microsoft·计算机·大模型·编程
神奇小梵4 小时前
安全和开发的需要了解的知识————下载内容的安全,和下载内容如何运行
android·windows·安全·个人开发
zhangfeng11335 小时前
Windows AMD显卡跑PyTorch
人工智能·pytorch·windows
楷哥爱开发5 小时前
如何在 Windows、macOS 和 Linux 上安装 scikit-learn (sklearn)
linux·windows·macos
2603_965148115 小时前
eBay商品数据API:寻找海外仓与价格洼地
大数据·人工智能·windows·python·microsoft
江畔柳前堤15 小时前
HBM:大语言模型时代的「算力血液」——从内存墙到带宽革命的深度拆解
服务器·人工智能·windows·目标检测·语言模型·自然语言处理·软件工程
天天进步201519 小时前
UI-TARS 源码解析 #22:二次开发实战:用 UI-TARS 做一个简单的 Windows 自动操作 Agent
windows·ui
啊哈一半醒20 小时前
Windows 虚拟机搭建 CentOS 全过程(2026 最新版 + 踩坑解决)
linux·windows·centos
new_zhou20 小时前
C++ 项目 AI 协作指南(Windows / MSVC 环境)
c++·人工智能·windows