Spring Boot 2.X(十九):集成 mybatis-plus 高效开发

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介:

前言

之前介绍了 SpringBoot 整合 Mybatis 实现数据库的增删改查操作,分别给出了 xml 和注解两种实现 mapper 接口的方式;虽然注解方式干掉了 xml 文件,但是使用起来并不优雅,本文将介绍 mybats-plus 的常用实例,简化常规的 CRUD 操作。

mybatis-plus

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

学习 mybatis-plus:https://mp.baomidou.com/guide

常用实例

1. 项目搭建

1.1 pom.xml

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
        <!-- 热部署模块 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>

1.2 application.yaml

# spring setting
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: zwqh@0258

1.3 实体类 UserEntity

@TableName(value="t_user")
public class UserEntity {

    @TableId(value="id",type=IdType.AUTO)
    private Long id;
    private String userName;
    private String userSex;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserSex() {
        return userSex;
    }
    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }
    
}

@TableName 指定数据库表名,否则默认查询表会指向 user_entity ;@TableId(value="id",type=IdType.AUTO) 指定数据库主键,否则会报错。

1.4 Dao层 UserDao

继承 BaseMapper,T表示对应实体类

public interface UserDao extends BaseMapper<UserEntity>{

}

1.5 启动类

在启动类添加 @MapperScan 就不用再 UserDao 上用 @Mapper 注解。

@SpringBootApplication
@MapperScan("cn.zwqh.springboot.dao")
public class SpringBootMybatisPlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatisPlusApplication.class, args);
    }

}

1.6 分页插件配置

@Configuration
public class MybatisPlusConfig {
     /**
     *   mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor page = new PaginationInterceptor();
        page.setDialectType("mysql");
        return page;
    }
 
}

2.示例

2.1 新增

新增用户
UserEntity user=new UserEntity();
user.setUserName("朝雾轻寒");
user.setUserSex("男");
userDao.insert(user);         

2.2 修改

根据id修改用户
UserEntity user=new UserEntity();
user.setUserName("朝雾轻晓");
user.setUserSex("男");
user.setId(25L);
userDao.updateById(user);
根据entity条件修改用户
UserEntity user=new UserEntity();
user.setUserSex("女");
userDao.update(user,new QueryWrapper<UserEntity>().eq("user_name", "朝雾轻寒"));

2.3 查询

根据id查询用户
UserEntity user = userDao.selectById(id);
根据entity条件查询总记录数
int count = userDao.selectCount(new QueryWrapper<UserEntity>().eq("user_sex", "男"));
根据 entity 条件,查询一条记录,返回的是实体
QueryWrapper<UserEntity> queryWrapper=new QueryWrapper<UserEntity>();
        UserEntity user=new UserEntity();
        user.setUserName("朝雾轻寒");
        user.setUserSex("男");
        queryWrapper.setEntity(user);
user = userDao.selectOne(queryWrapper);        

如果表内有两条或以上的相同数据则会报错,可以用来判断某类数据是否已存在

根据entity条件查询返回第一个字段的值(返回id列表)
QueryWrapper<UserEntity> queryWrapper=new QueryWrapper<UserEntity>();
        UserEntity user=new UserEntity();
        user.setUserSex("男");
        queryWrapper.setEntity(user);
List<Object> objs= userDao.selectObjs(queryWrapper);    
根据map条件查询返回多条数据
Map<String, Object> map=new HashMap<String, Object>();
        map.put("user_name", username);
        map.put("user_sex",sex);
List<UserEntity> list = userDao.selectByMap(map);        
根据entity条件查询返回多条数据(List)
Map<String, Object> map=new HashMap<String, Object>();
        map.put("user_sex","男");
List<UserEntity> list = userDao.selectList(new QueryWrapper<UserEntity>().allEq(map));        
根据entity条件查询返回多条数据(List> )
Map<String, Object> map=new HashMap<String, Object>();
        map.put("user_sex","男");
List<Map<String, Object>> list = userDao.selectMaps(new QueryWrapper<UserEntity>().allEq(map));
根据ID批量查询
List<Long> ids=new ArrayList<Long>();
        ids.add(1L);
        ids.add(2L);
        ids.add(3L);
List<UserEntity> list = userDao.selectBatchIds(ids);    

主键ID列表(不能为 null 以及 empty)

分页查询
Page<UserEntity> page=userDao.selectPage(new Page<>(1,5), new QueryWrapper<UserEntity>().eq("user_sex", "男"));
Page<Map<String, Object>> page=userDao.selectMapsPage(new Page<>(1,5), new QueryWrapper<UserEntity>().eq("user_sex", "男"));

需先配置分页插件bean,否则分页无效。如有pagehelper需先去除,以免冲突。

new Page<>(1,5),1表示当前页,5表示页面大小。

2.4 删除

根据id删除用户
userDao.deleteById(1);
根据entity条件删除用户
userDao.delete(new QueryWrapper<UserEntity>().eq("id", 1));
根据map条件删除用户
Map<String, Object> map=new HashMap<String, Object>();
        map.put("user_name", "zwqh");
        map.put("user_sex","男");
        userDao.deleteByMap(map);
根据ID批量删除
List<Long> ids=new ArrayList<Long>();
        ids.add(1L);
        ids.add(2L);
        ids.add(3L);
        userDao.deleteBatchIds(ids);

主键ID列表(不能为 null 以及 empty)

小结

本文介绍了 mybatis-plus 相关的 Mapper层 CRUD 接口实现,其还提供了 Service层 CRUD 的相关接口,有兴趣的小伙伴可以去使用下。 mybatis-plus 真正地提升了撸码效率。

其他学习要点:

  1. mybatis-plus 条件构造器
  2. lamda 表达式
  3. 常用注解
  4. ...

学习地址:https://mp.baomidou.com/guide/

示例代码

github

码云

非特殊说明,本文版权归 朝雾轻寒 所有,转载请注明出处.

原文标题:Spring Boot 2.X(十九):集成 mybatis-plus 高效开发

原文地址: https://www.zwqh.top/article/info/33

如果文章有不足的地方,欢迎提点建议,后续会完善~

如果文章对您有帮助,请给我点个赞哦~

关注下我的公众号,文章持续更新中...

相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
7天前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
8天前
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
12天前
|
前端开发 JavaScript Java
技术分享:使用Spring Boot3.3与MyBatis-Plus联合实现多层次树结构的异步加载策略
在现代Web开发中,处理多层次树形结构数据是一项常见且重要的任务。这些结构广泛应用于分类管理、组织结构、权限管理等场景。为了提升用户体验和系统性能,采用异步加载策略来动态加载树形结构的各个层级变得尤为重要。本文将详细介绍如何使用Spring Boot3.3与MyBatis-Plus联合实现这一功能。
50 2
|
23天前
|
Java 数据库连接 测试技术
SpringBoot 3.3.2 + ShardingSphere 5.5 + Mybatis-plus:轻松搞定数据加解密,支持字段级!
【8月更文挑战第30天】在数据驱动的时代,数据的安全性显得尤为重要。特别是在涉及用户隐私或敏感信息的应用中,如何确保数据在存储和传输过程中的安全性成为了开发者必须面对的问题。今天,我们将围绕SpringBoot 3.3.2、ShardingSphere 5.5以及Mybatis-plus的组合,探讨如何轻松实现数据的字段级加解密,为数据安全保驾护航。
73 1
|
24天前
|
SQL Java 数据库连接
Spring Boot联手MyBatis,打造开发利器:从入门到精通,实战教程带你飞越编程高峰!
【8月更文挑战第29天】Spring Boot与MyBatis分别是Java快速开发和持久层框架的优秀代表。本文通过整合Spring Boot与MyBatis,展示了如何在项目中添加相关依赖、配置数据源及MyBatis,并通过实战示例介绍了实体类、Mapper接口及Controller的创建过程。通过本文,你将学会如何利用这两款工具提高开发效率,实现数据的增删查改等复杂操作,为实际项目开发提供有力支持。
54 0
|
1月前
|
Web App开发 前端开发 关系型数据库
基于SpringBoot+Vue+Redis+Mybatis的商城购物系统 【系统实现+系统源码+答辩PPT】
这篇文章介绍了一个基于SpringBoot+Vue+Redis+Mybatis技术栈开发的商城购物系统,包括系统功能、页面展示、前后端项目结构和核心代码,以及如何获取系统源码和答辩PPT的方法。
|
1月前
|
Java 关系型数据库 MySQL
1、Mybatis-Plus 创建SpringBoot项目
这篇文章是关于如何创建一个SpringBoot项目,包括在`pom.xml`文件中引入依赖、在`application.yml`文件中配置数据库连接,以及加入日志功能的详细步骤和示例代码。
|
16天前
|
Java 数据库连接 开发者
MyBatis-Plus整合SpringBoot及使用
MyBatis-Plus为MyBatis提供了强大的增强,使得在Spring Boot项目中的数据访问层开发变得更加快捷和简便。通过MyBatis-Plus提供的自动CRUD、灵活的查询构造器和简洁的配置,开发者
29 0
|
1月前
|
数据库
elementUi使用dialog的进行信息的添加、删除表格数据时进行信息提示。删除或者添加成功的信息提示(SpringBoot+Vue+MybatisPlus)
这篇文章介绍了如何在基于SpringBoot+Vue+MybatisPlus的项目中使用elementUI的dialog组件进行用户信息的添加和删除操作,包括弹窗表单的设置、信息提交、数据库操作以及删除前的信息提示和确认。
elementUi使用dialog的进行信息的添加、删除表格数据时进行信息提示。删除或者添加成功的信息提示(SpringBoot+Vue+MybatisPlus)
|
1月前
|
Java 数据库 Spring
MyBatisPlus分页插件在SpringBoot中的使用
这篇文章介绍了如何在Spring Boot项目中配置和使用MyBatis-Plus的分页插件,包括创建配置类以注册分页拦截器,编写测试类来演示如何进行分页查询,并展示了测试结果和数据库表结构。
MyBatisPlus分页插件在SpringBoot中的使用