手把手教你Spring Boot整合Mybatis Plus和Swagger2

语言: CN / TW / HK
手把手教你Spring Boot整合Mybatis Plus和Swagger2

前言:如果你是初学者,请完全按照我的教程以及代码来搭建(文末会附上完整的项目代码包,你可以直接下载我提供的完整项目代码包然后自行体验!),为了照顾初学者所以贴图比较多,请耐心跟着教程来,希望这个项目Demo能给你一些帮助,如果觉得写的还可以请给个关注和点赞,谢谢!

题外话:这是我第一篇用markdown来写的博文,格式不好的地方请见谅

<?

2、在resources下新建application.yml文件,并添加如下配置

# 配置端口server: port: 8080#----------------druid数据源配置-----------------------spring: datasource: type: com.alibaba.druid.pool.DruidDataSource druid:  #这里跟pom里面mysql-connector版本相关8.0之后用com.mysql.cj.jdbc.Driver,之前用com.mysql.jdbc.Driver  driver-class-name: com.mysql.cj.jdbc.Driver  #这里改成你自己的数据库名称以及账号和密码  url: jdbc:mysql://127.0.0.1:3306/study?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true  username: root  password: 123456  initialSize: 10  minIdle: 10  maxActive: 30  # 配置获取连接等待超时的时间  maxWait: 60000  # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒  timeBetweenEvictionRunsMillis: 60000  # 配置一个连接在池中最小生存的时间,单位是毫秒  minEvictableIdleTimeMillis: 300000  validationQuery: SELECT 1 FROM DUAL  testWhileIdle: true  testOnBorrow: false  testOnReturn: false  # 打开PSCache,并且指定每个连接上PSCache的大小  poolPreparedStatements: true  # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙  #filters: stat,wall,log4j  # 通过connectProperties属性来打开mergeSql功能;慢SQL记录  connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000  # 合并多个DruidDataSource的监控数据  useGlobalDataSourceStat: true#----------------mybatis plus配置-----------------------mybatis-plus: # 

二、整合Swagger2

1、添加swagger的配置类SwaggerConfig.java

package com.example.study.config;import io.swagger.annotations.Api;import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.service.ApiKey;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.util.ArrayList;import java.util.List;/** * Swagger配置类 * * @author [email protected] * @date: 2021/2/22 10:02:00 */@[email protected]@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")public class SwaggerConfig { /** * 创建API应用 * apiInfo() 增加API相关信息 * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现, * 本例采用指定扫描的包路径来定义指定要建立API的目录。 * * @return */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(this.apiInfo()) .select() //设置选择器,选择带Api接口类的类 .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) //api包扫描 .apis(RequestHandlerSelectors.basePackage("com.example.study")) .paths(PathSelectors.any()) .build() .securitySchemes(securitySchemes()); } /** * 创建该API的基本信息(这些基本信息会展现在文档页面中) * 访问地址 * * @return ApiInfo */ private ApiInfo apiInfo() { return new ApiInfoBuilder().title("demo项目") .description("demo项目API文档") .termsOfServiceUrl("http://localhost") .version("1.0") .build(); } private List<ApiKey> securitySchemes() { List<ApiKey> apiKeyList= new ArrayList<>(); //apiKeyList.add(new ApiKey("token", "令牌", "header")); return apiKeyList; }}

2、新建controller包并且在controller包下新建IndexController.java

package com.example.study.controller;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * 首页控制器 * @author [email protected] * @date: 2021/2/22 10:02:00 */@Api(tags = "首页控制器")@RestControllerpublic class IndexController { @ApiOperation("首页html") @GetMapping("/") public String index(){ return "hello index"; }}

3、启动StudyApplication.java后访 src="https://img2020.cnblogs.com/blog/1543487/202102/1543487-20210223172631089-1507515509.png" alt="" loading="lazy">

三、整合Mybatis Plus

1、如图创建MybatisPlusConfi.java配置分页插件

package com.example.study.config;import com.baomidou.mybatisplus.annotation.DbType;import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * 配置MybatisPlus分页插件 * * @author [email protected] * @date: 2021/2/22 10:02:00 */@[email protected]("com.example.study.mapper")public class MybatisPlusConfig { /**  * Mybatis-plus3.4.0版本过后使用MybatisPlusInterceptor分页插件  * 注意:DbType.MYSQL必须为自己使用的数据库类型,否则分页不生效  */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() {  MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();  interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));  return interceptor; } /**  * 设置useDeprecatedExecutor = false 避免缓存出现问题  * @return  */ @Bean public ConfigurationCustomizer configurationCustomizer() {  return configuration -> configuration.setUseDeprecatedExecutor(false); }}

2、在数据库中创建测试表

CREATE TABLE `t_user` ( `id` bigint NOT NULL AUTO_INCREMENT, `name` varchar(32) DEFAULT NULL, `age` int DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8

3、创建实体类UserEntity.java

package com.example.study.model.entity;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableId;import com.baomidou.mybatisplus.annotation.TableName;import io.swagger.annotations.ApiModel;import io.swagger.annotations.ApiModelProperty;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.io.Serializable;/** * 用户信息实体类 * * @author [email protected] * @date: 2021/2/22 10:02:00 */@[email protected]@[email protected](value = "UserEntity", description = "用户实体")@TableName("t_user")public class UserEntity implements Serializable { private static final long serialVersionUID = 6928834261563057243L; /**  * 唯一标识,自增主键  */ @ApiModelProperty(value = "id") @TableId(value = "id", type = IdType.AUTO) private Long id; /**  * 姓名  */ @ApiModelProperty(value = "姓名") @TableField("name") private String name; /**  * 年龄  */ @ApiModelProperty(value = "年龄") @TableField("age") private Integer age;}

4、创建UserMapper.java

package com.example.study.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.example.study.model.entity.UserEntity;/** * @author [email protected] */public interface UserMapper extends BaseMapper<UserEntity> {}

5、创建UserService.java

package com.example.study.service;import com.baomidou.mybatisplus.extension.service.IService;import com.example.study.model.entity.UserEntity;/** * @author [email protected] */public interface UserService extends IService<UserEntity> {}

6、创建UserServiceImpl.java

package com.example.study.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;import com.example.study.model.entity.UserEntity;import com.example.study.mapper.UserMapper;import com.example.study.service.UserService;import org.springframework.stereotype.Service;/** * @author [email protected] */@Servicepublic class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {}

7、创建UserController.java(这里编译器会提示一些错误暂时不用管,因为缺少一些类的代码)

package com.example.study.controller;import com.baomidou.mybatisplus.core.metadata.IPage;import com.example.study.model.entity.UserEntity;import com.example.study.model.param.UserParam;import com.example.study.model.vo.ResponseVo;import com.example.study.service.UserService;import com.example.study.util.CommonQueryPageUtils;import com.example.study.util.BuildResponseUtils;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;/** * 用户控制器 * * @author [email protected] * @date: 2021/2/22 10:02:00 */@[email protected](tags = "用户控制器")public class UserController { @Autowired private UserService userService; @ApiOperation("新增") @PostMapping("user") public ResponseVo<?> add(UserEntity entity) {  return userService.save(entity) ? BuildResponseUtils.success() : BuildResponseUtils.error(); } @ApiOperation("通过id查询") @GetMapping("user/{id}") public ResponseVo<UserEntity> getById(@PathVariable String id) {  return BuildResponseUtils.buildResponse(userService.getById(id)); } @ApiOperation("修改") @PutMapping("user") public ResponseVo<?> update(UserEntity entity) {  return userService.updateById(entity) ? BuildResponseUtils.success() : BuildResponseUtils.error(); } @ApiOperation("通过id删除") @DeleteMapping("user/{id}") public ResponseVo<?> delete(@PathVariable String id) {  return userService.removeById(id) ? BuildResponseUtils.success() : BuildResponseUtils.error(); } @ApiOperation("分页查询") @GetMapping("userPage") public ResponseVo<IPage<UserEntity>> selectPage(UserParam param) {  return BuildResponseUtils.buildResponse(CommonQueryPageUtils.commonQueryPage(param, userService)); }}

8、创建枚举CodeMsgEnum.java

<.........

分享到: