前言

之前介绍了 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<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

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

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

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

Spring Boot 2.X(十九):集成 mybatis-plus 高效开发的更多相关文章

  1. Spring Boot 2.X(二):集成 MyBatis 数据层开发

    MyBatis 简介 概述 MyBatis 是一款优秀的持久层框架,支持定制化 SQL.存储过程以及高级映射.它采用面向对象编程的方式对数据库进行 CRUD 的操作,使程序中对关系数据库的操作更方便简 ...

  2. 学习Spring Boot:(七)集成Mybatis

    前面都是用的是spring data JPA,现在学习下Mybatis,而且现在Mybatis也像JPA那样支持注解形式了,也非常方便,学习一下. 数据库 mysql 5.7 添加依赖 在pom文件中 ...

  3. 学习Spring Boot:(十二)Mybatis 中自定义枚举转换器

    前言 在 Spring Boot 中使用 Mybatis 中遇到了字段为枚举类型,数据库存储的是枚举的值,发现它不能自动装载. 解决 内置枚举转换器 MyBatis内置了两个枚举转换器分别是:org. ...

  4. 学习Spring Boot:(十九)Shiro 中使用缓存

    前言 在 shiro 中每次去拦截请求进行权限认证的时候,都会去数据库查询该用户的所有权限信息, 这个时候就是有一个问题了,因为用户的权限信息在短时间内是不可变的,每次查询出来的数据其实都是重复数据, ...

  5. Spring Boot教程(十九)RESTful API单元测试

    下面针对该Controller编写测试用例验证正确性,具体如下.当然也可以通过浏览器插件等进行请求提交验证. @RunWith(SpringJUnit4ClassRunner.class) @Spri ...

  6. Spring Boot 2.X(十八):集成 Spring Security-登录认证和权限控制

    前言 在企业项目开发中,对系统的安全和权限控制往往是必需的,常见的安全框架有 Spring Security.Apache Shiro 等.本文主要简单介绍一下 Spring Security,再通过 ...

  7. Java Spring Boot VS .NetCore (五)MyBatis vs EFCore

    Java Spring Boot VS .NetCore (一)来一个简单的 Hello World Java Spring Boot VS .NetCore (二)实现一个过滤器Filter Jav ...

  8. Java Spring Boot VS .NetCore (九) Spring Security vs .NetCore Security

    Java Spring Boot VS .NetCore (一)来一个简单的 Hello World Java Spring Boot VS .NetCore (二)实现一个过滤器Filter Jav ...

  9. Spring Boot 2.X(十二):定时任务

    简介 定时任务是后端开发中常见的需求,主要应用场景有定期数据报表.定时消息通知.异步的后台业务逻辑处理.日志分析处理.垃圾数据清理.定时更新缓存等等. Spring Boot 集成了一整套的定时任务工 ...

随机推荐

  1. vue 生成 二维码 qrCode 插件 使用 方法

    首先安装方法:(--save 参数会改变package.json 推荐使用 下次直接install就行了) npm install --save qrcode 然后项目使用: import QRCod ...

  2. 2018-8-10-C#-判断文件编码

    title author date CreateTime categories C# 判断文件编码 lindexi 2018-08-10 19:16:52 +0800 2018-2-13 17:23: ...

  3. SVN常用命令之checkout

    官方解释,请参考:http://www.subversion.org.cn/svnbook/nightly/svn.ref.svn.c.checkout.html 常用检出命令: svn co htt ...

  4. laravel5数据库配置及其注意事项

    今天分享一个Laravel5数据库配置上的坑. Laravel5作为一套简洁.优雅的PHP Web开发框架(笑),唯一不足的一点就是中文手册或者说是资料比较少,虽然现在很多大神也开始普及这些东西,但是 ...

  5. 1626 - Brackets sequence——[动态规划]

    Let us define a regular brackets sequence in the following way: Empty sequence is a regular sequence ...

  6. P1020 从大到小排序

    题目描述 给你n个整数,请你按照从大到小的顺序输出它们. 输入格式 输入的第一行包含一个整数 \(n(1 \le n \le 10^3)\) ,用于表示元素的个数. 输入的第二行包含 \(n\) 个整 ...

  7. ASP.NET MVC 实现页落网资源分享网站+充值管理+后台管理(14)之会员中心管理

    源码下载地址:http://www.yealuo.com/Sccnn/Detail?KeyValue=c891ffae-7441-4afb-9a75-c5fe000e3d1c 会员中心,主要包含了会员 ...

  8. springboot-aop日志打印

    package com.cinc.ecmp.client; import com.cinc.ecmp.enums.BackResultEnum; import com.cinc.ecmp.except ...

  9. koa2--08.koa-session的使用

    首先安装 koa-session中间件 //koa-session的使用 const koa = require('koa'); var router = require('koa-router')( ...

  10. Linux统计文件/目录数量ls -l | grep "^-" | wc -l匹配开头和结尾,wc -c统计字符串长度

    Linux统计文件数量 ls -l | grep "^-" | wc -l “^-”  一般文件 “^d” 目录文件 shell/vim中^表示开头 cat repatterns ...