《一文读懂MyBatis-Plus:从入门到实战》

第一篇:初识MyBatis-Plus

什么是MyBatis-Plus?

MyBatis-Plus(简称MP)是MyBatis的增强工具,在MyBatis基础上只做增强不做改变,简化开发、提高效率。

为什么选择MyBatis-Plus?

  • 🚀 ​简化开发​:内置通用CRUD操作,减少30%以上代码量
  • ​功能丰富​:代码生成器、分页插件、性能分析插件等
  • 🔥 ​无缝兼容​:完全兼容原生MyBatis,学习成本低
  • 📈 ​社区活跃​:GitHub 20k+ Star,持续更新维护

第一篇:快速开始

  1. 添加依赖:
xml 复制代码
<!-- mybatis-plus 基于spring boot 2.x -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>

<!--jdbc -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>

<!--lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
    <scope>provided</scope>
</dependency>

<!--web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!--test -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<!--hutool -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.25</version>
</dependency>
  1. 配置数据源:
yaml 复制代码
server:
  port: 8080

spring:
  application:
    name: demo
  datasource:
    url: jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: xxx
    password: xxx

# mybatis-plus的配置
mybatis-plus:
  # 扫描xml路径
  mapper-locations: classpath*:/mapper/**/*.xml
  # 配置实体类别的,在xml中可以直接使用别名,无需写全路径
  type-aliases-package: com.it.domain
  # id自增策略的全局配置,光数据库设置id自增长可不行,还可以在这里配置
  global-config:
    db-config:
      id-type: auto

logging:
  level:
    root: info
    com.it: debug
  pattern:
    dateformat: "yyyy-MM-dd HH:mm:ss.SSS"

第二篇:基础CRUD操作

实体类配置

kotlin 复制代码
@Data
@TableName("user")  // 指定表名
public class User {
    @TableId(type = IdType.AUTO)  // 主键自增,可在yaml配置中指定全局的主键自增策略
    private Long id;
    private String name;
    private Integer age;
    @TableField("email")  // 指定字段名
    private String mail;
}

Mapper接口

csharp 复制代码
public interface UserMapper extends BaseMapper<User> {
    // 无需编写XML,继承BaseMapper即获得CRUD能力
}

基础操作示例

操作 代码示例
插入 userMapper.insert(user)
删除 userMapper.deleteById(1L)
修改 userMapper.updateById(user)
查询 userMapper.selectById(1L)
列表 userMapper.selectList(queryWrapper)

第三篇:条件构造器

Wrapper使用场景

构建复杂查询条件,替代原生MyBatis的动态SQL

查询常用方法

less 复制代码
// 1. 等值查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", "张三")
       .between("age", 20, 30);

// 2. 模糊查询
wrapper.like("name", "张");

// 3. 排序
wrapper.orderByDesc("create_time");

// 4. 复杂条件
wrapper.and(w -> w.gt("age", 18).or().isNotNull("email"));

Lambda写法(推荐)

perl 复制代码
LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
wrapper.eq(User::getName, "张三")
       .lt(User::getAge, 30);

更新常用方法

ini 复制代码
// 示例:将年龄大于 30 的用户名字改为 "管理员"
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.gt("age", 30); // 条件:age > 30

User updateUser = new User();
updateUser.setName("管理员");

userMapper.update(updateUser, wrapper);

Lambda写法(推荐)

sql 复制代码
// 示例:将名字包含 "张" 且年龄小于 20 的用户状态改为 0
userMapper.lambdaUpdate()
    .set(User::getStatus, 0)          // 更新字段
    .like(User::getName, "张")        // 条件:name LIKE '%张%'
    .lt(User::getAge, 20)            // 条件:age < 20
    .update();

第四篇:进阶功能

分页查询

  1. 添加分页插件:
java 复制代码
@Bean
public MybatisPlusInterceptor paginationInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
    return interceptor;
}
  1. 使用分页:
ini 复制代码
Page<User> page = new Page<>(1, 10);  // 当前页,每页条数
userMapper.selectPage(page, queryWrapper);

自动填充

  1. 标记填充字段:
ini 复制代码
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
  1. 实现填充处理器:
typescript 复制代码
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
    }
}

第五篇:代码生成器

一键生成全套代码

less 复制代码
// 推荐在idea中安装mybatis-plus插件,可以在idea插件的窗口中直接生成对应的一套代码,插件的头像是一个二次元美女图标
FastAutoGenerator.create(dataSourceConfig)
    .globalConfig(builder -> builder.author("作者"))
    .packageConfig(builder -> builder.parent("com.example"))
    .strategyConfig(builder -> builder.addInclude("user", "order"))
    .templateConfig(builder -> builder.disable(TemplateType.CONTROLLER))
    .execute();

生成内容包含:

  • 实体类(PO)
  • Mapper接口
  • XML映射文件
  • Service接口及实现
  • Controller(可选)

第六篇:最佳实践

1. 统一返回结果

less 复制代码
@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable Long id) {
        return Result.success(userService.getById(id));
    }
}

2. 逻辑删除配置

yaml 复制代码
mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: deleted  # 逻辑删除字段
      logic-delete-value: 1        # 删除值
      logic-not-delete-value: 0    # 未删除值

3. 性能优化建议

  • 避免使用select *,明确指定查询字段
  • 大数据量查询使用分页
  • 复杂查询考虑使用原生XML

附带:常用注解说明

1. @TableName 注解(表名映射)​

​属性​ ​类型​ ​默认值​ ​说明​ ​常用性​
value String "" 指定数据库表名(优先级最高) ⭐⭐⭐⭐⭐
schema String "" 数据库 schema(如 PostgreSQL) ⭐⭐
keepGlobalPrefix boolean false 是否保持全局表前缀配置
resultMap String "" 自定义结果映射 ID(XML 中定义)
autoResultMap boolean false 是否自动生成 resultMap ⭐⭐

​2. @TableField 注解(字段映射)​

​常用属性​

​属性​ ​类型​ ​默认值​ ​说明​ ​常用性​
value String "" 指定数据库字段名(优先级最高) ⭐⭐⭐⭐⭐
exist boolean true 是否为数据库字段(false 表示非表字段) ⭐⭐⭐⭐
fill Enum FieldFill.DEFAULT 字段自动填充策略(如 INSERTUPDATE ⭐⭐⭐⭐
select boolean true 是否参与查询(false 表示不查询) ⭐⭐⭐
condition String "" 字段的 WHERE 条件(如 age > 18 ⭐⭐

​不常用属性​

​属性​ ​类型​ ​默认值​ ​说明​ ​常用性​
jdbcType JdbcType JdbcType.UNDEFINED 指定 JDBC 类型(如 VARCHAR
numericScale String "" 数字类型的小数位数(如 2
el String "" SpEL 表达式(动态计算值)
keepGlobalFormat boolean false 是否保持全局字段格式配置
typeHandler Class UnknownTypeHandler.class 自定义类型处理器 ⭐⭐

​使用示例​

@TableName 示例​

kotlin 复制代码
@TableName(value = "t_user", schema = "public", autoResultMap = true)
public class User {
    // ...
}

@TableField 示例​

kotlin 复制代码
public class User {
    @TableField(value = "user_name", fill = FieldFill.INSERT)
    private String name;

    @TableField(exist = false)
    private String nonDbField;

    @TableField(condition = "age > 18")
    private Integer age;
}

​总结​

​分类​ ​核心作用​ ​高频使用属性​
​常用​ 基础字段映射、自动填充、逻辑控制 value, exist, fill, select
​不常用​ 特殊场景定制化 jdbcType, el, numericScale

📌 ​​总结​​:MyBatis-Plus让MyBatis开发效率提升50%,本文涵盖90%日常使用场景,收藏备用!一文读懂系统持续更新!

相关推荐
褚瑱琅3 分钟前
T-SQL语言的压力测试
开发语言·后端·golang
东方靖岚3 小时前
R语言的数据库交互
开发语言·后端·golang
uhakadotcom5 小时前
Python 量化计算入门:基础库和实用案例
后端·算法·面试
小萌新上大分5 小时前
SpringCloudGateWay
java·开发语言·后端·springcloud·springgateway·cloudalibaba·gateway网关
uhakadotcom5 小时前
使用Python获取Google Trends数据:2025年详细指南
后端·面试·github
uhakadotcom6 小时前
使用 Python 与 Google Cloud Bigtable 进行交互
后端·面试·github
直视太阳6 小时前
springboot+easyexcel实现下载excels模板下拉选择
java·spring boot·后端
追逐时光者6 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 33 期(2025年4.1-4.6)
后端·.net
灼华十一6 小时前
Golang系列 - 内存对齐
开发语言·后端·golang
兰亭序咖啡7 小时前
学透Spring Boot — 009. Spring Boot的四种 Http 客户端
java·spring boot·后端