【07】SpringBoot3 MybatisPlus 删除(Mapper)

SpringBoot3 MybatisPlus 删除

前言

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

删除 API

delete

官网 API:

java 复制代码
    /**
     * 根据 entity 条件,删除记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

Demo 示例:

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

        // 待删除的数据
        ClientEntity clientEntity = new ClientEntity();
        clientEntity.setId(301L);
        clientEntity.setClientId(301L);
        clientEntity.setRealName("根据ID更新-名称");
        // 用QueryWrapper包装实体,生成删除条件
        // 底层会拼接:WHERE id = 301 AND client_id = 301
        QueryWrapper<ClientEntity> queryWrapper = new QueryWrapper<>(clientEntity);
        clientMapper.delete(queryWrapper);

        // 验证,从数据库是否可以查到数据.
        ClientEntity clientEntity1 = clientMapper.selectById(301L);
        System.out.println("clientEntity1 = " + clientEntity1);
    }

输出日志:

deleteById

官网 API:

java 复制代码
    /**
     * 根据 ID 删除
     *
     * @param useFill 是否填充
     * @param obj      主键ID或实体
     * @since 3.5.7
     */
    default int deleteById(Object obj, boolean useFill) {
        Class<?> entityClass = ReflectionKit.getSuperClassGenericType(getClass(), BaseMapper.class, 0);
        Assert.notNull(entityClass, "entityClass must not be null");
        if (!entityClass.isAssignableFrom(obj.getClass()) && useFill) {
            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.");
            if (tableInfo.isWithLogicDelete() && tableInfo.isWithUpdateFill()) {
                T instance = tableInfo.newInstance();
                tableInfo.setPropertyValue(instance, keyProperty, OgnlOps.convertValue(obj, tableInfo.getKeyType()));
                return this.deleteById(instance);
            }
        }
        MapperProxyMetadata mapperProxyMetadata = MybatisUtils.getMapperProxy(this);
        SqlSession sqlSession = mapperProxyMetadata.getSqlSession();
        return sqlSession.delete(mapperProxyMetadata.getMapperInterface().getName() + Constants.DOT + SqlMethod.DELETE_BY_ID.getMethod(), obj);
    }

Demo 示例:

java 复制代码
    @Test
    public void testDeleteById() {
        int result = clientMapper.deleteById(302L);
        System.out.println("result = " + result);
    }

输出日志:

java 复制代码
2026-01-29T19:35:52.668+08:00  INFO 9652 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1014250816 wrapping com.mysql.cj.jdbc.ConnectionImpl@28b5d5dc] will not be managed by Spring
==>  Preparing: DELETE FROM client WHERE id=?
==> Parameters: 302(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@6d3ad37a]
result = 1

deleteById 实体类

官网 API:

java 复制代码
    /**
     * 根据实体(ID)删除
     *
     * @param entity 实体对象
     * @since 3.4.4
     */
    int deleteById(T entity);

Demo 示例:

java 复制代码
    @Test
    public void testDeleteById_02() {
        ClientEntity clientEntity = new ClientEntity();
        clientEntity.setId(302L);
        clientEntity.setClientId(302L);
        int result = clientMapper.deleteById(clientEntity);
        System.out.println("result = " + result);
    }

输出日志:

java 复制代码
2026-01-29T19:39:05.546+08:00  INFO 9512 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@499950630 wrapping com.mysql.cj.jdbc.ConnectionImpl@3fe98084] will not be managed by Spring
==>  Preparing: DELETE FROM client WHERE id=?
==> Parameters: 302(Long)
<==    Updates: 0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@308a9264]
result = 0
2026-01-29T19:39:05.592+08:00  INFO 9512 --- [springboot3-mybatisplus] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...

deleteByIds 批量

官网API

java 复制代码
    /**
     * 删除(根据ID或实体 批量删除)
     *
     * @param idList 主键ID列表或实体列表(不能为 null 以及 empty)
     * @since 3.5.7
     */
    default int deleteByIds(@Param(Constants.COLL) Collection<?> idList) {
        return deleteByIds(idList, true);
    }

Demo 示例:

java 复制代码
    @Test
    public void testDeleteByIds() {
        List<Long> ids = Arrays.asList(1L, 2L, 3L);
        int result = clientMapper.deleteBatchIds(ids);
        System.out.println("result = " + result);
    }

输出日志:

java 复制代码
2026-01-29T19:43:30.082+08:00  INFO 15452 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1683834425 wrapping com.mysql.cj.jdbc.ConnectionImpl@152891f8] will not be managed by Spring
==>  Preparing: DELETE FROM client WHERE id IN ( ? , ? , ? )
==> Parameters: 1(Long), 2(Long), 3(Long)
<==    Updates: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@16e07bae]
result = 3

deleteByMap

官网 API:

java 复制代码
    /**
     * 根据 columnMap 条件,删除记录
     *
     * @param columnMap 表字段 map 对象
     */
    default int deleteByMap(Map<String, Object> columnMap) {
        return this.delete(Wrappers.<T>query().allEq(columnMap));
    }

Demo 示例:

java 复制代码
2026-01-29T19:47:05.846+08:00  INFO 4684 --- [springboot3-mybatisplus] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@492135521 wrapping com.mysql.cj.jdbc.ConnectionImpl@46d148bd] 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: 50(Integer)
<==    Columns: id, client_id, user_no, user_password, nick_name, real_name, created_time, upated_time
<==        Row: 50, 50, MDDWAW2AuQ, GXzMEWqXxFIxNsfIOkyEoEdhtJhuPcGn, 太阳花,我要渲染你的微笑, 乐之, 2026-01-26 07:22:25, 2026-01-26 07:22:25
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3c9f4376]
删除之前 ===>>> clientEntity = ClientEntity(id=50, clientId=50, userNo=MDDWAW2AuQ, userPassword=GXzMEWqXxFIxNsfIOkyEoEdhtJhuPcGn, nickName=太阳花,我要渲染你的微笑, realName=乐之, createdTime=Mon Jan 26 07:22:25 CST 2026, upatedTime=Mon Jan 26 07:22:25 CST 2026)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@11309dd4] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@2070199213 wrapping com.mysql.cj.jdbc.ConnectionImpl@46d148bd] will not be managed by Spring
==>  Preparing: DELETE FROM client WHERE (id = ?)
==> Parameters: 50(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@11309dd4]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2e0163cb] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1797821749 wrapping com.mysql.cj.jdbc.ConnectionImpl@46d148bd] 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: 50(Integer)
<==      Total: 0
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2e0163cb]
删除之后 ===>>> clientEntity = null
2026-01-29T19:47:05.979+08:00  INFO 4684 --- [springboot3-mybatisplus] [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...

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

相关推荐
island13145 分钟前
CANN GE(图引擎)深度解析:计算图优化管线、内存静态规划与异构 Stream 调度机制
c语言·开发语言·神经网络
云姜.8 分钟前
线程和进程的关系
java·linux·jvm
是码龙不是码农9 分钟前
支付防重复下单|5 种幂等性设计方案(从初级到架构级)
java·架构·幂等性
曹牧9 分钟前
Spring Boot:如何在Java Controller中处理POST请求?
java·开发语言
heartbeat..10 分钟前
JVM 性能调优流程实战:从开发规范到生产应急排查
java·运维·jvm·性能优化·设计规范
浅念-13 分钟前
C++入门(2)
开发语言·c++·经验分享·笔记·学习
WeiXiao_Hyy13 分钟前
成为 Top 1% 的工程师
java·开发语言·javascript·经验分享·后端
User_芊芊君子19 分钟前
CANN010:PyASC Python编程接口—简化AI算子开发的Python框架
开发语言·人工智能·python
苏渡苇19 分钟前
优雅应对异常,从“try-catch堆砌”到“设计驱动”
java·后端·设计模式·学习方法·责任链模式
团子的二进制世界26 分钟前
G1垃圾收集器是如何工作的?
java·jvm·算法