前言:本博客主要是记录自己学习的过程,方便日后查看,当然也希望能够帮到大家。
一, 说明:SpringBoot 2.7.0 整合MyBatis-Plus 3.5.2详细教程,并整合Alibaba Druid数据源,使用MySQL(版本5.7)数据库,使用hutool开源工具.
1.MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。官网地址:戳我学习MyBatis-Plus
2.Druid由阿里团队研发,后捐赠给Apache基金会,Druid是一个高效的数据查询系统,主要解决的是对于大量的基于时序的数据进行聚合查询。数据可以实时摄入,进入到Druid后立即可查,同时数据是几乎是不可变。通常是基于时序的事实事件,事实发生后进入Druid,外部系统就可以对该事实进行查询。官网地址:戳我学习Druid
3.Hutool是国内程序员在工作中总结和积累而成的一套小而全的工具类库,相比于Guava,它更符合国内开发者的需求。Hutool首次发布于2014年,最新版本为5.6.5,到目前为止已经在github上收获了1.9万个赞。官网地址:戳我学习Hutool
二, 项目开始: 1.搭建项目为方便编写后续整合项目,直接搭建微服务式目录结构,新建父Maven项目如下图:
如上图目录结构说明:
Spring Boot-demo ├── common-demo-- 工具类及通用代码模块 ├── mybatisplus-demo -- 整合MyBatisPlus模块 ├── sms-demo -- 整合阿里云短信模块(后续更新) └── other-- 整合其他模块(后续更新)1.引入相关依赖:
UTF-8 UTF-8 2.7.0 1.2.73 1.2.11 3.5.2 5.1.47 1.4.2 2.7.0 5.4.1 3.12.0 org.springframework.boot spring-boot-dependencies ${spring-boot.version} pom import com.alibaba fastjson ${fastjson.version} com.alibaba druid-spring-boot-starter ${druid.version} com.baomidou mybatis-plus-boot-starter ${mybatisPlus.version} mysql mysql-connector-java ${mysql.version} org.springframework.boot spring-boot-starter-validation ${validation.version} cn.hutool hutool-all ${hutool.version} org.apache.commons commons-lang3 ${lang3.version}
注:包含基础依赖,直接引入项目即可,后续继续增加其他依赖。
2.Cmmon-demo-- 工具类及通用代码模块介绍Cmmon目录结构如下图:
Cmmon-demo ├── enums-- 枚举类包 ├── page -- 分页对象类包 ├── response -- 响应类包 └── other-- 其他包(后续更新)
引入相关依赖:
dependencies>
org.springframework.boot
spring-boot-starter-validation
org.apache.commons
commons-lang3
cn.hutool
hutool-all
com.baomidou
mybatis-plus-boot-starter
enums枚举类:
package com.wisesliu.enums;
import java.util.HashMap;
import java.util.Map;
public enum GlobalErrorCode {
SUCCESS(200, "操作成功"),
FAIL(-2, "操作失败"),
UNKNOWN(-1, "未知的错误"),
;
private int errorCode;
private String errorMsg;
private static final Map errorCodes = new HashMap<>();
static {
for (GlobalErrorCode errorCode : GlobalErrorCode.values()) {
errorCodes.put(errorCode.getErrorCode(), errorCode);
}
}
GlobalErrorCode(int errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public static GlobalErrorCode valueOf(int code) {
GlobalErrorCode globalErrorCode = errorCodes.get(code);
if (globalErrorCode != null) {
return globalErrorCode;
}
return UNKNOWN;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
}
page分页类对象:
(1)前端请求分页类:
public class FrontPage{ @NotNull(message = "每页显示条数不能为空") private Integer size; @NotNull(message = "当前页数不能为空") private Integer current; private String order; private Boolean asc; public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public Integer getCurrent() { return current; } public void setCurrent(Integer current) { this.current = current; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } public Boolean getAsc() { return asc; } public void setAsc(Boolean asc) { this.asc = asc; } public Page getPage() { Page page = new Page<>(); page.setCurrent(this.current); page.setSize(this.size); // 多排序字段处理 if (StringUtils.isNotBlank(this.order)) { List orders = new ArrayList<>(); List orderList = ListUtil.toList(this.order.split(",")); for (String str : orderList) { OrderItem orderItem = new OrderItem(); orderItem.setColumn(str); orderItem.setAsc(Objects.nonNull(this.asc) ? this.asc : false); orders.add(orderItem); } page.setOrders(orders); } return page; } }
(2)后端相应分页类:
public class CustomPage{ private Long current; private Long size; private Long total; private Long records; private List rows; public Long getCurrent() { return current; } public void setCurrent(Long current) { this.current = current; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } public Long getRecords() { return records; } public void setRecords(Long records) { this.records = records; } public List getRows() { return rows; } public void setRows(List rows) { this.rows = rows; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } public CustomPage(Page page) { this.current = page.getCurrent(); this.size = page.getSize(); this.records = page.getTotal(); this.rows = page.getRecords(); this.total = page.getPages(); } }
response后端响应类对象:
(1)基础响应类对象:
public class BaseResponse {
private Integer status = 200;
private String message;
public BaseResponse() {
}
public BaseResponse(Integer status, String message) {
this.status = status;
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public static BaseResponse success(String moreInfo) {
int status = GlobalErrorCode.SUCCESS.getErrorCode();
return new BaseResponse(status, moreInfo);
}
public static BaseResponse success() {
int status = GlobalErrorCode.SUCCESS.getErrorCode();
String msg = GlobalErrorCode.SUCCESS.getErrorMsg();
return new BaseResponse(status, msg);
}
public static BaseResponse error(GlobalErrorCode errorCode, String moreInfo) {
int status = errorCode.getErrorCode();
return new BaseResponse(status, moreInfo);
}
public static BaseResponse error(GlobalErrorCode errorCode) {
int status = errorCode.getErrorCode();
String msg = errorCode.getErrorMsg();
return new BaseResponse(status, msg);
}
public static BaseResponse error(String moreInfo) {
int status = GlobalErrorCode.FAIL.getErrorCode();
return new BaseResponse(status,moreInfo);
}
}
(1)返回响应类对象:
public class ObjectRestResponse3.mybatisplus-demo模块extends BaseResponse { T data; private ObjectRestResponse() { } private ObjectRestResponse(int status, String msg, T data) { super(status, msg); this.data = data; } private ObjectRestResponse(int status, String msg) { super(status, msg); } public T getData() { return data; } public void setData(T data) { this.data = data; } public static ObjectRestResponse success(String moreInfo, T data) { int status = GlobalErrorCode.SUCCESS.getErrorCode(); return new ObjectRestResponse<>(status, moreInfo, data); } public static ObjectRestResponse success(T data) { int status = GlobalErrorCode.SUCCESS.getErrorCode(); String msg = GlobalErrorCode.SUCCESS.getErrorMsg(); return new ObjectRestResponse<>(status, msg, data); } public static ObjectRestResponse error(GlobalErrorCode errorCode, String moreInfo, T data) { int status = errorCode.getErrorCode(); return new ObjectRestResponse<>(status, moreInfo, data); } public static ObjectRestResponse error(GlobalErrorCode errorCode, T data) { int status = errorCode.getErrorCode(); String msg = errorCode.getErrorMsg(); return new ObjectRestResponse<>(status, msg, data); } }
mybatisplus目录结构如下图:
mybatisplus-demo ├── config-- 配置类类包 ├── entity--实体类包 ├── mapper-- 数据操作接口类包 ├── service-- 数据操作实现接口类包 ├── controller-- 端点接口类包 └── -- 其他包(后续更新)
引入相关依赖:
org.springframework.boot spring-boot-starter-web org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine com.alibaba fastjson com.alibaba druid-spring-boot-starter com.baomidou mybatis-plus-boot-starter mysql mysql-connector-java common-demo com.wisesliu 1.0.0
详细配置文件:application.yml
server:
port: 8001
spring:
application:
name: mybatisPlus-demo-server
#配置数据源
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 连接池的配置信息
druid:
# 初始化大小,最小,最大
initial-size: 5
min-idle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECt 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 配置DruidStatFilter
web-stat-filter:
enabled: true
url-pattern: "
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
注:分页配置类,必须实现,详细查看官方文档:戳我学习MyBatis-Plus
entity
entity ├── form-- 表单提交类 ├── param--请求参数类 └── -- 对象类
form类
@Data
public class UserForm implements Serializable {
@NotBlank
private String username;
private String password;
@NotBlank
private String fullname;
@NotBlank
private String mobile;
private static final long serialVersionUID = -8978461117607917157L;
}
param类
@Data
public class UserParam implements Serializable {
private String username;
private String fullname;
private String mobile;
}
user类
@Data
@TableName("t_user")
public class User implements Serializable {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("username")
private String username;
@TableField("password")
private String password;
@TableField("fullname")
private String fullname;
@TableField("mobile")
private String mobile;
private static final long serialVersionUID = 4791568101260386736L;
}
mapper
@Mapper public interface UserMapper extends BaseMapper{ }
service
public interface UserService extends IService{ }
serviceImpl
@Service public class UserServiceImpl extends ServiceImplimplements UserService { }
controller
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@GetMapping("/page")
public ObjectRestResponse> page(@Valid FrontPage page, UserParam param) {
QueryWrapper wrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(param.getUsername())) {
wrapper.lambda().like(User::getUsername, param.getUsername());
}
if (StringUtils.isNotBlank(param.getFullname())) {
wrapper.lambda().like(User::getFullname, param.getFullname());
}
if (StringUtils.isNotBlank(param.getMobile())) {
wrapper.lambda().like(User::getMobile, param.getMobile());
}
Page pageList = userService.page(page.getPage(), wrapper);
return ObjectRestResponse.success(new CustomPage<>(pageList));
}
@GetMapping("add")
public ObjectRestResponse add(UserForm form) {
User user = new User();
BeanUtils.copyProperties(form, user);
user.setPassword(StringUtils.isNotBlank(user.getPassword()) ? user.getPassword() : IdUtil.simpleUUID());
userService.save(user);
return ObjectRestResponse.success("操作成功", null);
}
}
启动类
**
* @author jixia
* @date 2022/6/16 20:15
* @description
*/
@SpringBootApplication
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
3.Druid效果:
1.Druid访问地址:
http://127.0.0.1:8001/druid/login.html
登录效果:
SQL执行监控效果:
4.查询效果:请求地址:
http://127.0.0.1:8001/user/page?current=1&size=10
请求方式::
GET
参数::
current:当前页 size:分页数量
完整代码地址:正在搭建中,后续公布。
注:此工程包含多个module,本文所用代码均在mybatisplus-demo模块下
后记:本次分享到此结束,本博主水平有限,难免有错误或遗漏之处,望大家指正和谅解,欢迎评论留言。



