当前位置: 首页 > news >正文

【MybatisPlus】SpringBoot3整合MybatisPlus

目录

一、依赖

二、yml 配置

三、xml 配置

四、config 配置

五、使用

实体类

Mapper.java

Service.java

ServiceImpl.java

Mapper.xml

六、逻辑删除


一、依赖

            <!-- springboot3 / mybatis-plus 配置,mybatis使用 3.5.16 版本,避免版本冲突 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.16</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-spring-boot3-starter</artifactId><version>${mybatis-plus-spring-boot3.version}</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-jsqlparser</artifactId><version>${mybatis-plus-spring-boot3.version}</version></dependency>
        <mybatis-plus-spring-boot3.version>3.5.10</mybatis-plus-spring-boot3.version>

二、yml 配置

application.yml

# MyBatis配置
#mybatis:
#  # 搜索指定包别名
#  typeAliasesPackage: com.leslie.**.domain
#  # 配置mapper的扫描,找到所有的mapper.xml映射文件
#  mapperLocations: classpath*:mapper/**/*Mapper.xml
#  # 加载全局的配置文件
#  configLocation: classpath:mybatis/mybatis-config.xml# mybatis-plus配置
mybatis-plus:# 配置mapper的扫描,找到所有的mapper.xml映射文件mapper-locations: classpath*:mapper/**/*Mapper.xml# 搜索指定包别名,多个用【;】分隔type-aliases-package: com.leslie.**.domain;global-config:#数据库相关配置db-config:#主键类型  AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";id-type: AUTOlogic-delete-value: 1 # 逻辑删除时,is_delete 为删除的值logic-not-delete-value: 0 # 逻辑删除时,is_delete 为未删除的值banner: false#原生配置configuration:map-underscore-to-camel-case: truecache-enabled: falsecall-setters-on-nulls: true
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #日志输出# PageHelper分页插件
pagehelper:helperDialect: mysqlsupportMethodsArguments: trueparams: count=countSql

三、xml 配置

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 全局参数 --><settings><!-- 使全局的映射器启用或禁用缓存 --><setting name="cacheEnabled"             value="true"   /><!-- 允许JDBC 支持自动生成主键 --><setting name="useGeneratedKeys"         value="true"   /><!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 --><setting name="defaultExecutorType"      value="SIMPLE" /><!-- 指定 MyBatis 所用日志的具体实现 --><setting name="logImpl"                  value="SLF4J"  /><!-- 使用驼峰命名法转换字段 --><!-- <setting name="mapUnderscoreToCamelCase" value="true"/> --></settings></configuration>

四、config 配置

MybatisPlusConfig.java

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;/*** Mybatis Plus 配置*/
@EnableTransactionManagement(proxyTargetClass = true)
@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();// 分页插件interceptor.addInnerInterceptor(paginationInnerInterceptor());// 乐观锁插件interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());// 阻断插件interceptor.addInnerInterceptor(blockAttackInnerInterceptor());return interceptor;}/*** 分页插件,自动识别数据库类型 <a href="https://baomidou.com/guide/interceptor-pagination.html">...</a>*/public PaginationInnerInterceptor paginationInnerInterceptor() {PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();// 设置数据库类型为mysqlpaginationInnerInterceptor.setDbType(DbType.MYSQL);// 设置最大单页限制数量,默认 500 条,-1 不受限制paginationInnerInterceptor.setMaxLimit(-1L);return paginationInnerInterceptor;}/*** 乐观锁插件 <a href="https://baomidou.com/guide/interceptor-optimistic-locker.html">...</a>*/public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {return new OptimisticLockerInnerInterceptor();}/*** 如果是对全表的删除或更新操作,就会终止该操作 <a href="https://baomidou.com/guide/interceptor-block-attack.html">...</a>*/public BlockAttackInnerInterceptor blockAttackInnerInterceptor() {return new BlockAttackInnerInterceptor();}
}

五、使用

实体类

import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDate;/*** @author Leslie Lee* @version 2003/04/01* @date 1956/09/12*/
@Data
@TableName("test")
@ExcelIgnoreUnannotated
public class TestEntity implements Serializable {@Serialprivate static final long serialVersionUID = 1L;//    @TableId(type = IdType.AUTO)private Integer id;@ExcelProperty("姓名")private String name;@ExcelProperty("性别")private String sex;private LocalDate createTime;private LocalDate updateTime;@TableLogicprivate Integer isDelete;}

@TableName("表名") :当实体类名与数据库表名不一致时,需用此注解来标明对应的表

@TableId(type = IdType.AUTO):如果 id 为自增,可用此注解进行标识

Mapper.java

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.leslie.ai.domain.TestEntity;
import org.apache.ibatis.annotations.Mapper;import java.util.List;/*** Mapper 测试** @author Leslie Lee* @TIME 1956/09/12* @Version 2003/04/01*/
@Mapper
public interface TestEntityMapper extends BaseMapper<TestEntity> {List<TestEntity> queryTestEntityList(TestEntity o);
}

@Mapper:动态代理,与 Mapper.xml 对应

extends BaseMapper<实体类>:提供基本的增删改查方法

Service.java

里面的方法需与 Mapper.java 中对应,deleteById 方法实现是用的自带的删除方法,所以不对应也不影响,但是需要重写 sql 语句的方法都要对应

import com.leslie.ai.domain.TestEntity;import java.util.List;/*** Service** @author Leslie Lee* @TIME 1956/09/12* @Version 2003/04/01*/
public interface TestEntityService {List<TestEntity> queryTestEntityList(TestEntity o);int deleteById(Integer id);
}

ServiceImpl.java

直接使用 this.baseMapper 可以拿到Mapper.java 中对应的方法

import com.leslie.ai.domain.TestEntity;
import com.leslie.ai.mapper.TestEntityMapper;
import com.leslie.ai.service.TestEntityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import java.util.List;/*** ServiceImpl** @author Leslie Lee* @TIME 1956/09/12* @Version 2003/04/01*/
@Service
public class TestEntityServiceImpl extends ServiceImpl<TestEntityMapper, TestEntity> implements TestEntityService {@Overridepublic List<TestEntity> queryTestEntityList(TestEntity o) {return this.baseMapper.queryTestEntityList(o);}@Overridepublic int deleteById(Integer id) {return this.baseMapper.deleteById(id);}
}

Mapper.xml

此类文件放在 resources 文件夹下,建议文件路径与实体类一致

namespace:对应实体类全路径

resultMap:方法返回参数,实体类使用表字段名驼峰命名时,不需要再写字段对应关系

<?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.leslie.ai.mapper.TestEntityMapper"><!-- 实体类  --><resultMap type="TestEntity" id="TestEntityResult">
<!--        <result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>--></resultMap><!-- sql语句 --><sql id="selectTestEntityList"></sql><!-- 方法 --><select id="queryTestEntityList" parameterType="TestEntity" resultMap="TestEntityResult"><include refid="selectTestEntityList"/><where>  <if test="fieldName != null and fieldName != ''"> and tableFieldName like concat('%', #{fieldName}, '%')</if><if test="startDate != null and startDate != ''">and applicationDate &gt;= #{startDate}</if><if test="endDate != null and endDate != ''">and applicationDate &lt;= #{endDate}</if></where></select>
</mapper>

六、逻辑删除

通过更改表的某一字段状态,区分是否删除

实体类

实体类增加字段:isDelete ===> 对应表字段 is_delete     (也可以用其他字段,对应就行)

添加注解:@TableLogic

    @TableLogicprivate Integer isDelete;

还可以添加两个字段:创建时间、修改时间

    private LocalDate createTime; // create_timeprivate LocalDate updateTime; // update_time

yml 配置

      logic-delete-value: 1 # 逻辑删除时,is_delete 为删除的值logic-not-delete-value: 0 # 逻辑删除时,is_delete 为未删除的值

数据库

创建时间、修改时间,字段名就用下面的两个,

然后设置默认值 CURRENT_TIMESTAMP(2)

修改时间会在表数据变动时自动更新

                                                                Leslie Lee 随笔


文章转载自:

http://Wc4AFNEn.zsyrk.cn
http://w98OlYmP.zsyrk.cn
http://yfB2aagv.zsyrk.cn
http://gWFsmjE8.zsyrk.cn
http://k3oT5TrV.zsyrk.cn
http://hPq8YI6O.zsyrk.cn
http://qh65YG8M.zsyrk.cn
http://PMkzJVGb.zsyrk.cn
http://fL6yJddb.zsyrk.cn
http://bQfIx15V.zsyrk.cn
http://tL4Ggxmw.zsyrk.cn
http://c3aCa2Qo.zsyrk.cn
http://kl5rl0cn.zsyrk.cn
http://5ggTq2R1.zsyrk.cn
http://5XEZf1zl.zsyrk.cn
http://QWs863ds.zsyrk.cn
http://bIs6L4eE.zsyrk.cn
http://51oDOTTB.zsyrk.cn
http://jrPU4YxV.zsyrk.cn
http://qeaI2JbI.zsyrk.cn
http://T7VvUCXg.zsyrk.cn
http://HUvkDcCa.zsyrk.cn
http://pDrDOcZn.zsyrk.cn
http://qrrfRXK1.zsyrk.cn
http://wV49j6Gp.zsyrk.cn
http://A7gpQAiR.zsyrk.cn
http://t8wl7G7u.zsyrk.cn
http://cGNjnfzw.zsyrk.cn
http://BiZaq0b4.zsyrk.cn
http://Xr008gSO.zsyrk.cn
http://www.dtcms.com/a/375665.html

相关文章:

  • 如何在FastAPI中玩转“时光倒流”的数据库事务回滚测试?
  • MySQL数据库面试题整理
  • PostgreSQL 大对象管理指南:pg_largeobject 从原理到实践
  • 传统项目管理的局限性有哪些
  • 内核函数:copy_process
  • 《UE5_C++多人TPS完整教程》学习笔记50 ——《P51 多人游戏中的俯仰角(Pitch in Multiplayer)》
  • RL【5】:Monte Carlo Learning
  • 深度解析HTTPS:从加密原理到SSL/TLS的演进之路
  • minio 文件批量下载
  • 【算法专题训练】19、哈希表
  • AJAX入门-URL、参数查询、案例查询
  • 安装ultralytics
  • Eino ChatModel 组件指南摘要
  • 腾讯codebuddy-cli重磅上线-国内首家支持全形态AI编程工具!
  • 基于PCL(Point Cloud Library)的点云高效处理方法
  • UVa1302/LA2417 Gnome Tetravex
  • STC Link1D电脑端口无法识别之升级固件
  • 【C++】LLVM-mingw + VSCode:Windows 开发攻略
  • SRM系统有哪些核心功能?企业该如何科学选型?
  • LINUX99 centos8:网络 yum配置;shell:while [ $i -ne 5 ];do let i++ done
  • 【陇剑杯2025】密码复现(部分)
  • 漫谈《数字图像处理》之图像自适应阈值处理
  • Melon: 基于marker基因的三代宏基因组分类和定量软件
  • 水题记录1.7
  • JVM 执行引擎详解!
  • lua中 string.match返回值
  • 2025-安装集成环境XAMPP
  • 整体设计 之 绪 思维导图引擎 :思维价值链分层评估的 思维引导和提示词导航 之 引 认知系统 之6之 序 认知元架构 之1(豆包助手 之3)
  • 【教学类-07-10】20250909中3班破译电话号码(手写数字版、撕贴版、头像剪贴底纹版、抄写填空版)
  • 【初阶数据结构】算法复杂度