百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

MyBatis-Plus 与 Spring Boot 整合及常用功能详解

bigegpt 2025-05-15 16:30 3 浏览


以下是 MyBatis-Plus 与 Spring Boot 整合的详细用法,包含依赖配置、核心配置、代码示例和常用功能演示:

一、添加依赖

在 pom.xml 中引入 MyBatis-Plus 和数据库驱动(以 MySQL 为例):

<dependencies>

<!-- Spring Boot 启动器 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<!-- MyBatis-Plus 核心依赖 -->

<dependency>

<groupId>com.baomidou</groupId>

<artifactId>mybatis-plus-boot-starter</artifactId>

<version>3.5.3</version> <!-- 最新版本请查看官网 -->

</dependency>

<!-- MySQL 驱动(8.x 版本) -->

<dependency>

<groupId>com.mysql</groupId>

<artifactId>mysql-connector-j</artifactId>

<scope>runtime</scope>

</dependency>

<!-- Spring Boot 测试 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

</dependency>

</dependencies>

二、配置文件(application.yml)

配置数据源和 MyBatis-Plus 的扫描路径、日志等:

spring:

datasource:

driver-class-name: com.mysql.cj.jdbc.Driver # MySQL 8+ 驱动类名

url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=Asia/Shanghai

username: root

password: your_password

# (可选)配置连接池(如 HikariCP)

# hikari:

# minimum-idle: 5

# maximum-pool-size: 15

mybatis-plus:

mapper-locations: classpath:mapper/**/*.xml # Mapper XML 文件路径(可选,复杂查询时使用)

type-aliases-package: com.example.entity # 实体类包路径(自动扫描别名)

configuration:

log-impl:
org.apache.ibatis.logging.stdout.StdOutImpl # 打印 SQL 日志(开发环境使用)

global-config:

db-config:

logic-delete-field: is_deleted # 逻辑删除字段名(全局配置)

logic-delete-value: 1 # 逻辑删除标识:已删除(值)

logic-not-delete-value: 0 # 逻辑删除标识:未删除(值)

三、启动类配置

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 接口所在的包:

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.mybatis.spring.annotation.MapperScan;

@SpringBootApplication

@MapperScan("com.example.mapper") // 扫描 Mapper 接口包

public class MybatisPlusDemoApplication {

public static void main(String[] args) {

SpringApplication.run(MybatisPlusDemoApplication.class, args);

}

}

四、实体类(Entity)

使用 MyBatis-Plus 注解映射数据库表和字段:

package com.example.entity;

import com.baomidou.mybatisplus.annotation.*;

import lombok.Data;

@Data

@TableName("tb_user") // 映射数据库表名

public class User {

@TableId(type = IdType.AUTO) // 主键策略(自增)

private Long id;

private String name;

private Integer age;

private String email;

// 逻辑删除字段(标记为 @TableLogic)

@TableLogic

private Integer isDeleted;

// 自动填充字段(插入/更新时自动填充)

@TableField(fill = FieldFill.INSERT)

private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)

private Date updateTime;

}

五、Mapper 接口

继承 BaseMapper<T> 接口,自动获得 CRUD 方法:

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import com.example.entity.User;

public interface UserMapper extends BaseMapper<User> {

// 无需编写基础 CRUD 方法,直接继承 BaseMapper 即可

// 复杂查询可在对应的 XML 中编写

}

六、配置分页插件(MybatisPlusInterceptor)

MyBatis-Plus 3.4.0+ 推荐使用 MybatisPlusInterceptor 配置分页、乐观锁等插件:

package com.example.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;

import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class MyBatisPlusConfig {

// 配置分页插件

@Bean

public MybatisPlusInterceptor mybatisPlusInterceptor() {

MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

// 添加分页插件

interceptor.addInnerInterceptor(new PaginationInnerInterceptor());

// (可选)添加乐观锁插件

// interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

return interceptor;

}

}

七、Service 层使用示例

1. 基础 CRUD 操作

package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.entity.User;

import com.example.mapper.UserMapper;

import org.springframework.stereotype.Service;

@Service

public class UserService extends ServiceImpl<UserMapper, User> {

// 继承 ServiceImpl 后,自动获得基础服务方法(如 save、update、list 等)

// 示例:查询年龄大于 20 且邮箱不为空的用户

public List<User> getUsersByAgeAndEmail() {

LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();

wrapper.gt(User::getAge, 20)

.isNotNull(User::getEmail);

return baseMapper.selectList(wrapper);

}

}

2. 分页查询

@Service

public class UserService {

public Page<User> getUsersByPage(int currentPage, int pageSize) {

Page<User> page = new Page<>(currentPage, pageSize); // currentPage 从 1 开始

baseMapper.selectPage(page, null); // 查询所有数据并分页

return page; // 包含总记录数和当前页数据

}

}

3. 逻辑删除

@Service

public class UserService {

public void deleteUser(Long id) {

baseMapper.deleteById(id); // 逻辑删除(自动更新 is_deleted 为 1)

}

}

八、复杂查询:XML 与 MyBatis-Plus 混合使用

如果需要编写复杂 SQL,可以在 Mapper 接口中声明方法,并在 XML 中实现:

// Mapper 接口声明方法

public interface UserMapper extends BaseMapper<User> {

List<User> selectUsersWithCondition(@Param("age") Integer age);

}

<!-- resources/mapper/UserMapper.xml -->

<mapper namespace="com.example.mapper.UserMapper">

<select id="selectUsersWithCondition" resultType="com.example.entity.User">

SELECT * FROM tb_user

<where>

<if test="age != null">age > #{age}</if>

</where>

</select>

</mapper>

九、常用功能总结

功能

实现方式

基础 CRUD

继承 BaseMapper 或 ServiceImpl,直接调用 selectById、insert 等方法

条件查询

使用 QueryWrapper 或 LambdaQueryWrapper 构建动态条件

分页查询

配置
PaginationInnerInterceptor,使用 Page 对象

逻辑删除

实体类字段添加 @TableLogic,全局配置逻辑删除值

自动填充

配置 MetaObjectHandler,实现字段插入 / 更新时自动填充时间等信息

乐观锁

添加
OptimisticLockerInnerInterceptor 插件,实体类字段添加 @Version

十、测试验证

在测试类中注入 Service 并验证功能:

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import com.example.entity.User;

import com.example.service.UserService;

@SpringBootTest

public class UserServiceTest {

@Autowired

private UserService userService;

@Test

public void testInsertUser() {

User user = new User();

user.setName("张三");

user.setAge(25);

user.setEmail("zhangsan@example.com");

boolean result = userService.save(user);

System.out.println("插入结果:" + result);

}

}

通过以上步骤,即可完成 MyBatis-Plus 与 Spring Boot 的整合,并利用其特性大幅简化数据库操作。MyBatis-Plus 在保留 MyBatis 灵活性的同时,减少了基础代码的编写量,适合快速开发场景。

相关推荐

得物可观测平台架构升级:基于GreptimeDB的全新监控体系实践

一、摘要在前端可观测分析场景中,需要实时观测并处理多地、多环境的运行情况,以保障Web应用和移动端的可用性与性能。传统方案往往依赖代理Agent→消息队列→流计算引擎→OLAP存储...

warm-flow新春版:网关直连和流程图重构

本期主要解决了网关直连和流程图重构,可以自此之后可支持各种复杂的网关混合、多网关直连使用。-新增Ruoyi-Vue-Plus优秀开源集成案例更新日志[feat]导入、导出和保存等新增json格式支持...

扣子空间体验报告

在数字化时代,智能工具的应用正不断拓展到我们工作和生活的各个角落。从任务规划到项目执行,再到任务管理,作者深入探讨了这款工具在不同场景下的表现和潜力。通过具体的应用实例,文章展示了扣子空间如何帮助用户...

spider-flow:开源的可视化方式定义爬虫方案

spider-flow简介spider-flow是一个爬虫平台,以可视化推拽方式定义爬取流程,无需代码即可实现一个爬虫服务。spider-flow特性支持css选择器、正则提取支持JSON/XML格式...

solon-flow 你好世界!

solon-flow是一个基础级的流处理引擎(可用于业务规则、决策处理、计算编排、流程审批等......)。提供有“开放式”驱动定制支持,像jdbc有mysql或pgsql等驱动,可...

新一代开源爬虫平台:SpiderFlow

SpiderFlow:新一代爬虫平台,以图形化方式定义爬虫流程,不写代码即可完成爬虫。-精选真开源,释放新价值。概览Spider-Flow是一个开源的、面向所有用户的Web端爬虫构建平台,它使用Ja...

通过 SQL 训练机器学习模型的引擎

关注薪资待遇的同学应该知道,机器学习相关的岗位工资普遍偏高啊。同时随着各种通用机器学习框架的出现,机器学习的门槛也在逐渐降低,训练一个简单的机器学习模型变得不那么难。但是不得不承认对于一些数据相关的工...

鼠须管输入法rime for Mac

鼠须管输入法forMac是一款十分新颖的跨平台输入法软件,全名是中州韵输入法引擎,鼠须管输入法mac版不仅仅是一个输入法,而是一个输入法算法框架。Rime的基础架构十分精良,一套算法支持了拼音、...

Go语言 1.20 版本正式发布:新版详细介绍

Go1.20简介最新的Go版本1.20在Go1.19发布六个月后发布。它的大部分更改都在工具链、运行时和库的实现中。一如既往,该版本保持了Go1的兼容性承诺。我们期望几乎所...

iOS 10平台SpriteKit新特性之Tile Maps(上)

简介苹果公司在WWDC2016大会上向人们展示了一大批新的好东西。其中之一就是SpriteKitTileEditor。这款工具易于上手,而且看起来速度特别快。在本教程中,你将了解关于TileE...

程序员简历例句—范例Java、Python、C++模板

个人简介通用简介:有良好的代码风格,通过添加注释提高代码可读性,注重代码质量,研读过XXX,XXX等多个开源项目源码从而学习增强代码的健壮性与扩展性。具备良好的代码编程习惯及文档编写能力,参与多个高...

Telerik UI for iOS Q3 2015正式发布

近日,TelerikUIforiOS正式发布了Q32015。新版本新增对XCode7、Swift2.0和iOS9的支持,同时还新增了对数轴、不连续的日期时间轴等;改进TKDataPoin...

ios使用ijkplayer+nginx进行视频直播

上两节,我们讲到使用nginx和ngixn的rtmp模块搭建直播的服务器,接着我们讲解了在Android使用ijkplayer来作为我们的视频直播播放器,整个过程中,需要注意的就是ijlplayer编...

IOS技术分享|iOS快速生成开发文档(一)

前言对于开发人员而言,文档的作用不言而喻。文档不仅可以提高软件开发效率,还能便于以后的软件开发、使用和维护。本文主要讲述Objective-C快速生成开发文档工具appledoc。简介apple...

macOS下配置VS Code C++开发环境

本文介绍在苹果macOS操作系统下,配置VisualStudioCode的C/C++开发环境的过程,本环境使用Clang/LLVM编译器和调试器。一、前置条件本文默认前置条件是,您的开发设备已...