GVKun编程网logo

Spring Boot整合Mybatis Plus和Swagger2的教程详解(springboot整合mybatis-plus)

8

在本文中,我们将详细介绍SpringBoot整合MybatisPlus和Swagger2的教程详解的各个方面,并为您提供关于springboot整合mybatis-plus的相关解答,同时,我们也将为

在本文中,我们将详细介绍Spring Boot整合Mybatis Plus和Swagger2的教程详解的各个方面,并为您提供关于springboot整合mybatis-plus的相关解答,同时,我们也将为您带来关于sprigboot整合mybatis-plus、Spring boot 、mybatis 和 swagger 整合、spring boot整合mybatis+mybatis-plus的示例代码、spring boot整合mybatis-plus的有用知识。

本文目录一览:

Spring Boot整合Mybatis Plus和Swagger2的教程详解(springboot整合mybatis-plus)

Spring Boot整合Mybatis Plus和Swagger2的教程详解(springboot整合mybatis-plus)

这篇文章主要介绍了Spring Boot整合Mybatis Plus和Swagger2的教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

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

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

一、pom.xml和application.yml

1、pom.xml中添加相关依赖,这里我把我的pom.xml代码贴出来

4.0.0org.springframework.bootspring-boot-starter-parent2.4.3com.examplestudy0.0.1-SNAPSHOTstudyDemo project for Spring Boot1.88.0.133.4.11.0.92.9.25.5.8org.springframework.bootspring-boot-starter-weborg.projectlomboklomboktrueorg.springframework.bootspring-boot-starter-testtestMysqLmysql-connector-javaruntime${MysqL.version}com.baomidoumybatis-plus-boot-starter${mybatisPlus.version}com.baomidoumybatis-plus-generator${mybatisPlus.version}com.alibabadruid${druid.version}io.springfoxspringfox-swagger2${swagger.version}io.springfoxspringfox-swagger-ui${swagger.version}cn.hutoolhutool-all${hutool.version}org.springframework.bootspring-boot-maven-pluginorg.projectlomboklombok

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: # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置) mapper-locations: classpath:mapper/*.xml configuration: # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射 map-underscore-to-camel-case: true # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段 call-setters-on-nulls: true # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用 log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 实体扫描,多个package用逗号或者分号分隔(这里更改为你的实体类存放路径) typeAliasesPackage: com.example.study.model.entity global-config: db-config: #主键类型 AUTO:"数据库ID自增" INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID"; id-type: auto #字段策略 IGnorED:"忽略判断" NOT_NULL:"非 NULL 判断") NOT_EMPTY:"非空判断" field-strategy: NOT_EMPTY #数据库类型 db-type: MysqL # 逻辑删除配置 # 删除前 logic-not-delete-value: 1 # 删除后 logic-delete-value: 0 #----------------swagger配置----------------------- swagger: #生产环境改为false(改为false后swagger-ui.html则无法访问) enable: true #解决Swagger2 异常 NumberFormatException:For input string:"" logging: level: io: swagger: models: parameters: AbstractSerializableParameter: ERROR

二、整合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 154594742@qq.com * @date: 2021/2/22 10:02:00 */ @Configuration @EnableSwagger2 @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的基本信息(这些基本信息会展现在文档页面中) * 访问地址:http://ip:端口/swagger-ui.html * * @return ApiInfo */ private ApiInfo apiInfo() { return new ApiInfoBuilder().title("demo项目") .description("demo项目api文档") .termsOfServiceUrl("http://localhost") .version("1.0") .build(); } private List securitySchemes() { List 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 154594742@qq.com * @date: 2021/2/22 10:02:00 */ @Api(tags = "首页控制器") @RestController public class IndexController { @ApiOperation("首页html") @GetMapping("/") public String index(){ return "hello index"; } }

3、启动StudyApplication.java后访问http://localhost:8080/swagger-ui.html,出现第二图所示则表示swagger整合完成

三、整合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 154594742@qq.com * @date: 2021/2/22 10:02:00 */ @Configuration @MapperScan("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 154594742@qq.com * @date: 2021/2/22 10:02:00 */ @Data @NoArgsConstructor @AllArgsConstructor @ApiModel(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 154594742@qq.com */ public interface UserMapper extends BaseMapper { }

5、创建UserService.java

package com.example.study.service; import com.baomidou.mybatisplus.extension.service.IService; import com.example.study.model.entity.UserEntity; /** * @author 154594742@qq.com */ public interface UserService extends IService { }

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 154594742@qq.com */ @Service public class UserServiceImpl extends ServiceImpl 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 154594742@qq.com * @date: 2021/2/22 10:02:00 */ @RestController @Api(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 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> selectPage(UserParam param) { return buildresponseUtils.buildresponse(CommonQueryPageUtils.commonQueryPage(param, userService)); } }

8、创建枚举CodeMsgEnum.java

package com.example.study.enums; /** * 异常类code常量(code值不要重复) * * @author 154594742@qq.com * @date: 2021/2/22 9:42:00 */ public enum CodeMsgEnum { //请求成功 SUCCESS("0","成功!"), //系统异常 FAIL("1","失败!"), //以下是业务异常 LOGIN_NO_PASS("1001","用户名或密码错误"), ; /** * 状态码 */ public String code; /** * 状态码对应信息 */ public String msg; CodeMsgEnum(String code, String msg) { this.code = code; this.msg = msg; } }

9、创建统一的返回结果类ResponseVo.java

package com.example.study.model.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * 统一的返回对象VO * * @author 154594742@qq.com * @date: 2021/2/22 10:02:00 */ @Data @NoArgsConstructor @AllArgsConstructor @ApiModel(value = "ResponseVo", description = "统一的返回对象") public class ResponseVo implements Serializable { private static final long serialVersionUID = 7748070653645596712L; /** * 状态码 */ @ApiModelProperty(value = "状态码") private String code; /** * 状态码对应描述信息 */ @ApiModelProperty(value = "状态码对应描述信息") private String msg; /** * 数据 */ @ApiModelProperty(value = "数据") private T data; }

10、创建常量类QueryMethodConstant.java

package com.example.study.constant; /** * mybatis plus常用的查询方式 * @author 154594742@qq.com * @date 2021/2/23 11:24 */ public interface QueryMethodConstant { /** * 相同 */ String EQ = "EQ"; /** * 不相同 */ String NE = "NE"; /** * 相似,左右模糊(like '%值%') */ String LIKE = "LIKE"; /** * 相似,左模糊(like '%值') */ String LIKE_LIFT = "LIKE_LIFT"; /** * 相似,右模糊(like '值%') */ String LIKE_RIGHT = "LIKE_RIGHT"; /** * 不相似 (not like '%值%') */ String NOT_LIKE = "NOT_LIKE"; /** * 大于 */ String GT = "GT"; /** * 大于等于 */ String GE = "GE"; /** * 小于 */ String LT = "LT"; /** * 小于等于 */ String LE = "LE"; }

11、创建自定义注解QueryMethod.java(用于后续的通用分页查询工具类)

package com.example.study.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 查询方式的自定义注解 * @author 154594742@qq.com * @date 2021/2/23 11:24 */ @Retention(RetentionPolicy.RUNTIME) @Target(value = ElementType.FIELD) public @interface QueryMethod { /** * 字段名 */ String field() default ""; /** * 匹配方式 */ String method() default ""; }

12、创建构建返回结果工具类buildresponseUtils.java

package com.example.study.util; import com.example.study.enums.CodeMsgEnum; import com.example.study.model.vo.ResponseVo; /** * 构建返回结果工具类 * * @author 154594742@qq.com * @date: 2021/2/22 10:02:00 */ public final class buildresponseUtils { /** * 构建正确请求的response * * @return ResponseVo 统一的返回结果 */ public static ResponseVo> success() { ResponseVo> response = new ResponseVo(); response.setCode(CodeMsgEnum.SUCCESS.code); response.setMsg(CodeMsgEnum.SUCCESS.msg); return response; } /** * 构建业务异常的response * @param codeMsgEnum 枚举 * @return ResponseVo 统一的返回结果 */ public static ResponseVo> success(CodeMsgEnum codeMsgEnum) { ResponseVo> response = new ResponseVo(); response.setCode(codeMsgEnum.code); response.setMsg(codeMsgEnum.msg); return response; } /** * 构建自定义code和msg的业务异常 * * @param code 自定义code * @param msg 自定义msg * @return ResponseVo 统一的返回结果 */ public static ResponseVo> success(String code, String msg) { ResponseVo> response = new ResponseVo(); response.setCode(code); response.setMsg(msg); return response; } /** * 构建系统异常的response(只用于系统异常) * @return ResponseVo 统一的返回结果 */ public static ResponseVo> error() { ResponseVo> response = new ResponseVo(); response.setCode(CodeMsgEnum.FAIL.code); response.setMsg(CodeMsgEnum.FAIL.msg); return response; } /** * 构建返回结果 * @param obj 结果数据 * @param 结果数据的泛型 * @return ResponseVo 统一的返回结果 */ public static ResponseVo buildresponse(T obj) { ResponseVo response = new ResponseVo(); response.setData(obj); response.setCode(CodeMsgEnum.SUCCESS.code); response.setMsg(CodeMsgEnum.SUCCESS.msg); return response; } }

13、创建分页查询工具类CommonQueryPageUtils.java(本人自己封装的,功能可能不是很完善,但是基本的单表查询够用了)

package com.example.study.util; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.Metadata.IPage; import com.baomidou.mybatisplus.core.Metadata.OrderItem; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import com.example.study.annotation.QueryMethod; import com.example.study.constant.QueryMethodConstant; import com.example.study.model.param.PageParam; import java.lang.reflect.Field; import java.util.Locale; /** * 分页查询工具类 * * @author 154594742@qq.com * @date: 2021/2/22 10:02:00 */ public final class CommonQueryPageUtils { /** * 正序 */ private static final String ASC = "asc"; /** * 倒序 */ private static final String DESC = "desc"; /** * 通用的带排序功能的分页查询 */ public static IPage commonQueryPage(PageParam param, IService service) { //构建page //根据传入的排序设置order //排序字段(格式:字段名:排序方式,字段名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc) Page page = new Page(param.getPage(), param.getLimit()); String orders = param.getorders(); if (StringUtils.isNotBlank(orders)) { String[] splitArr = orders.split(","); for (String str : splitArr) { if (StringUtils.isBlank(str)) { continue; } String[] strArr = str.split(":"); if (strArr.length != 2 || StringUtils.isBlank(strArr[0]) || StringUtils.isBlank(strArr[1])) { continue; } if (ASC.equals(strArr[1].toLowerCase(Locale.ROOT))) { page.addOrder(OrderItem.asc(strArr[0])); continue; } if (DESC.equals(strArr[1].toLowerCase(Locale.ROOT))) { page.addOrder(OrderItem.desc(strArr[0])); } } } //根据自定义注解构建queryWrapper QueryWrapper queryWrapper = new QueryWrapper(); Class extends PageParam> clazz = param.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { //设置对象的访问权限,保证对private的属性可以访问 field.setAccessible(true); QueryMethod annotation = field.getAnnotation(QueryMethod.class); try { //属性没有值则跳过 if (null == field.get(param)) { continue; } //没有加@QueryMethod 默认属性名为字段名,默认匹配方式为eq if (null == annotation) { queryWrapper.eq(field.getName(), field.get(param)); continue; } switch (annotation.method()) { case QueryMethodConstant.EQ: queryWrapper.eq(annotation.field(), field.get(param)); break; case QueryMethodConstant.NE: queryWrapper.ne(annotation.field(), field.get(param)); break; case QueryMethodConstant.LIKE: queryWrapper.like(annotation.field(), field.get(param)); break; case QueryMethodConstant.LIKE_LIFT: queryWrapper.likeLeft(annotation.field(), field.get(param)); break; case QueryMethodConstant.LIKE_RIGHT: queryWrapper.likeRight(annotation.field(), field.get(param)); break; case QueryMethodConstant.GT: queryWrapper.gt(annotation.field(), field.get(param)); break; case QueryMethodConstant.GE: queryWrapper.ge(annotation.field(), field.get(param)); break; case QueryMethodConstant.LT: queryWrapper.lt(annotation.field(), field.get(param)); break; case QueryMethodConstant.LE: queryWrapper.le(annotation.field(), field.get(param)); break; default: ; } } catch (illegalaccessexception e) { e.printstacktrace(); } } return service.page(page, queryWrapper); } }

14、创建统一的分页查询请求参数类PageParam.java

package com.example.study.model.param; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.LinkedHashMap; /** * 统一的分页查询请求参数 * * @author 154594742@qq.com * @date 2021/2/22 17:24 */ @Data @ApiModel(value = "PageParam", description = "分页参数") public class PageParam { /** * 页码 */ @ApiModelProperty(value = "页码,不传则默认1") private Integer page = 1; /** * 每页条数 */ @ApiModelProperty(value = "每页条数,不传则默认10") private Integer limit = 10; /** * 排序字段(格式:字段名:排序方式,字段名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc) */ @ApiModelProperty(value = "排序字段(格式:字段名:排序方式,字段名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc)") private String orders; }

15、创建用户查询条件类UserParam.java继承PageParam(以后分页查询的参数类都要继承PageParam)

package com.example.study.model.param; import com.example.study.annotation.QueryMethod; import com.example.study.constant.QueryMethodConstant; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * 用户查询条件类(需要根据哪些字段查询就添加哪些字段) * @author 154594742@qq.com * @date 2021/2/22 17:24 */ @Data @ApiModel(value = "UserParam", description = "用户查询条件") public class UserParam extends PageParam { /** * 通过@QueryMethod注解来控制匹配的方式,这里查询条件为 name like ‘%值%' */ @ApiModelProperty(value = "姓名") @QueryMethod(field = "name", method = QueryMethodConstant.LIKE) private String name; /** * 这里没有@QueryMethod注解则如果age有值,则默认查询条件为 age=值 */ @ApiModelProperty(value = "年龄") private Integer age; /** * 假如要查询 (值1 25 */ @ApiModelProperty(value = "年龄下限") @QueryMethod(field = "age", method = QueryMethodConstant.GT) private String minAge; @ApiModelProperty(value = "年龄上限") @QueryMethod(field = "age", method = QueryMethodConstant.LT) private String maxAge; }

16、先在数据库中添加几条测试数据,然后启动项目后打开http://localhost:8080/swagger-ui.html

insert into `t_user`(`id`,`name`,`age`) values (1,'小二',20), (2,'张三',20), (3,'李四',20), (4,'王五',35), (5,'小六',18);

17、按上图填入查询条件,然后点击“Execute”执行

返回的Response body:

{ "code": "0", "msg": "成功!", "data": { "records": [ { "id": 5, "name": "小六", "age": 18 }, { "id": 1, "name": "小二", "age": 20 }, { "id": 2, "name": "张三", "age": 20 }, { "id": 3, "name": "李四", "age": 20 } ], "total": 4, "size": 10, "current": 1, "orders": [ { "column": "age", "asc": true } ], "optimizeCountsql": true, "hitCount": false, "countId": null, "maxLimit": null, "searchCount": true, "pages": 1 } }

通过上面的返回结果可以看出我们带条件带排序的的分页查询功能是ok的!!!

感谢你看完了此篇博文,如果有什么问题可以评论留言,附上完整代码 点击下载完整代码包

到此这篇关于Spring Boot整合Mybatis Plus和Swagger2的文章就介绍到这了,更多相关Spring Boot整合Mybatis Plus和Swagger2内容请搜索小编以前的文章或继续浏览下面的相关文章希望大家以后多多支持小编!

sprigboot整合mybatis-plus

sprigboot整合mybatis-plus

 

 

 

 

Spring boot 、mybatis 和 swagger 整合

Spring boot 、mybatis 和 swagger 整合

文件路径

添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>wonder</groupId>
    <artifactId>skyRainbow</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>

        <!--spring boot 的依赖 START-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--spring boot 的依赖 END-->

        <!--mybatis 的依赖 START-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!--mybatis 的依赖 END-->

        <!--mysql 的依赖 START-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--mysql 的依赖 END-->

        <!--jsp 的依赖 START-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!--jsp 的依赖 END-->

        <!--swagger 的依赖 START-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!--swagger 的依赖 END-->

    </dependencies>

    <build>
        <!--配置文件读取路径-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
            <include>**/*.properties</include>
</includes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

添加 spring boot 启动文件

package lf;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;


@SpringBootApplication
@MapperScan("lf.mapper") // mapper层的路径
@PropertySource({"classpath:mybatis.properties",
                 "classpath:datasource.properties"})// 读取.properties 文件路径
public class SkyRainbowApplication {

    public static void main(String[] args) {
        /**
         * Spring boot 程序入口
         */
        SpringApplication.run(SkyRainbowApplication.class,args);
   }
}

添加 swagger 启动文件

package lf.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api_lf(){
        return  new Docket(DocumentationType.SWAGGER_2)
                .groupName("api_lf")
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(false)
                .pathMapping("/")
                .select()
                .paths(or(regex("/lf/.*")))
                .build()
                .apiInfo(apiInfo());

    }

    /**
     *  构建api文档详细信息
     */
    private ApiInfo apiInfo() {
        ApiInfo apiInfo = new ApiInfo(
                "甘雨路 API",// 标题
                "API 描述说明",//描述
                "1.0",//版本
                "NO terms of service",
                "lf@qq.com",// 创建人
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }



}

添加控制层

package lf.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import lf.entity.BsdUser;
import lf.service.BsdUserSerive;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Date;

@Controller
@RequestMapping(value="${modulePath}/page")
@Api(description = "页面跳转控制器")
public class PageController {
    @Resource
    private BsdUserSerive userSerive;
    /**
     * 进入公司主页
     */
    @RequestMapping(value = "/company",method = RequestMethod.GET)
    public String gotoCompanyPage(Model model,@RequestParam @ApiParam("用户id") Long id){
        BsdUser user = userSerive.getUserById(id);
        model.addAttribute("time",new Date());
        model.addAttribute("loginName",user.getName());
        return "main";
    }

}
package lf.controller;

import io.swagger.annotations.*;
import lf.entity.BsdUser;
import lf.entity.utils.CommonDTO;
import lf.service.BsdUserSerive;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@Api(description = "用户控制器")//swagger注解用于类
@Controller // 控制器注解
@RequestMapping(value="${modulePath}/user")
public class UserController {

    @Resource
    private BsdUserSerive userSerive;

    @ResponseBody
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public CommonDTO<BsdUser> getUserbyId(@RequestParam @ApiParam("用户id") Long id){
        CommonDTO<BsdUser> detailDTO = new CommonDTO<>(0,1);
        try {
            BsdUser user = userSerive.getUserById(id);
            detailDTO.setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            detailDTO.setStatus(1);
            detailDTO.setCode(400);
            detailDTO.setMsg("获取用户信息异常:"+e.getMessage());

        }

        return detailDTO;
    }


}

添加实体类

package lf.entity.utils;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.Map;


@ApiModel(description = "详情DTO")
public class CommonDTO<T>{

    @ApiModelProperty(value = "提示信息")
    private String msg;

    @ApiModelProperty(value = "0 代表无错误 1代表有错误")
    private Integer status;

    @ApiModelProperty(value = "总记录")
    private Integer total;

    @ApiModelProperty(value = "业务数据")
    private T data;

    @ApiModelProperty(value = "200 代表无错误 400代表有错误--->加入这个字段是原生需求")
    private Integer code;


    @ApiModelProperty(value = "当前页码")
    private Integer pageNo = 1;

    @ApiModelProperty(value = "当前页码,默认:10")
    private Integer pageSize = Integer.valueOf(10); // 页面大小,设置为“-1”表示不进行分页(分页无效)

    @ApiModelProperty(value = "总记录数")
    private long totalSize;// 总记录数,设置为“-1”表示不查询总数



    private Map<String,Object> DataMap;

    public CommonDTO(Integer status) {
        if (status == 0){
            this.status = status;
            this.code = 200;
            this.msg = "操作成功";
        }
        this.data = null;
    }




    public CommonDTO(Integer status, Integer total) {
        if (status == 0){
            this.status = status;
            this.code = 200;
            this.msg = "操作成功";
        }
        this.data = null;
        this.total = total;
    }

    public Map<String, Object> getDataMap() {
        return DataMap;
    }

    public void setDataMap(Map<String, Object> dataMap) {
        DataMap = dataMap;
    }

    public Integer getCode() {return code;}

    public void setCode(Integer code) {this.code = code;}

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


    public Integer getPageNo() {
        return (pageNo!=null&&pageNo>0)?pageNo:-1;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public Integer getPageSize() {
        return (pageSize!=null&&pageSize>0)?pageSize:10;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }


    /**
     * 获取设置总数
     * @return
     */
    public long getTotalSize() {
        return totalSize;
    }

    /**
     * 设置数据总数
     * @param count
     */
    public void setTotalSize(long totalSize) {
        this.totalSize = totalSize;
        if (pageSize >= totalSize){
            pageNo = 1;
        }
    }


    @Override
    public String toString() {
        return "CommonDTO{" +
                "msg=''" + msg + ''\'''' +
                ", status=" + status +
                ", total=" + total +
                ", data=" + data +
                ''}'';
    }
}
package lf.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;

@ApiModel(description = "用户实体")
public class BsdUser implements Serializable {
    @ApiModelProperty("主键")
    private Long id;
    @ApiModelProperty("组织id")
    private Long orgId;
    @ApiModelProperty("用户类型(0,品牌商1,服务商2,零售商,3客服)")
    private Integer userType;
    @ApiModelProperty("登录名")
    private String loginName;
    @ApiModelProperty("电话")
    private String phone;
    @ApiModelProperty("姓名")
    private String name;
    @ApiModelProperty("简称")
    private String shortName;
    @ApiModelProperty("密码")
    private String password;
    @ApiModelProperty("联系人")
    private String contactUserName;
    @ApiModelProperty("地址")
    private String address;
    @ApiModelProperty("经度")
    private BigDecimal longitude;
    @ApiModelProperty("纬度")
    private BigDecimal latitude;
    @ApiModelProperty("级别(0,普通会员,1,一级会员,2,二级会员,3三级会员,4,四级会员,5,五级会员)")
    private Integer level;
    @ApiModelProperty("状态(0,无效,1有效,2未审核,3审核未通过)")
    private Integer state;
    @ApiModelProperty("银行卡")
    private String bankCard;
    @ApiModelProperty("总积分")
    private Long totalPoints;
    @ApiModelProperty("上级组织id")
    private Long superiorId;
    @ApiModelProperty("创建人id")
    private Long createdBy;
    @ApiModelProperty("最后更新人")
    private Long lastUpdatedBy;
    @ApiModelProperty("创建日期")
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date createdDate;
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    @ApiModelProperty("最后更新日期")
    private Date lastUpdatedDate;
    @ApiModelProperty("软删除标志")
    private Integer removeFlag;
    @ApiModelProperty("图片地址")
    private String imgUrl;
    @ApiModelProperty("消费总金额")
    private BigDecimal totalPaymentAmount;
    @ApiModelProperty("佣金")
    private BigDecimal commission;
    @ApiModelProperty("运费")
    private BigDecimal freight;
    @ApiModelProperty("编号")
    private String code;
    @ApiModelProperty("已经支付定金")
    private Long depositPaid;
    @ApiModelProperty("注册信息附件信息传")
    private String registerAttachmentUrl;
    @ApiModelProperty("支付密码")
    private String payPassWord;
    @ApiModelProperty("钱包余额")
    private BigDecimal balance;
    @ApiModelProperty("现金卷余额")
    private BigDecimal cashRoll;

    private static final long serialVersionUID = 1L;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getOrgId() {
        return orgId;
    }

    public void setOrgId(Long orgId) {
        this.orgId = orgId;
    }

    public Integer getUserType() {
        return userType;
    }

    public void setUserType(Integer userType) {
        this.userType = userType;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code == null ? null : code.trim();
    }

    public String getLoginName() {
        return loginName;
    }

    public void setLoginName(String loginName) {
        this.loginName = loginName == null ? null : loginName.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }

    public String getShortName() {
        return shortName;
    }

    public void setShortName(String shortName) {
        this.shortName = shortName == null ? null : shortName.trim();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getContactUserName() {
        return contactUserName;
    }

    public void setContactUserName(String contactUserName) {
        this.contactUserName = contactUserName == null ? null : contactUserName.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    public BigDecimal getLongitude() {
        return longitude;
    }

    public void setLongitude(BigDecimal longitude) {
        this.longitude = longitude;
    }

    public String getRegisterAttachmentUrl() {
        return registerAttachmentUrl;
    }

    public void setRegisterAttachmentUrl(String registerAttachmentUrl) {
        this.registerAttachmentUrl = registerAttachmentUrl == null ? null : registerAttachmentUrl.trim();
    }

    public BigDecimal getLatitude() {
        return latitude;
    }

    public void setLatitude(BigDecimal latitude) {
        this.latitude = latitude;
    }

    public Integer getLevel() {
        return level;
    }

    public void setLevel(Integer level) {
        this.level = level;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl == null ? null : imgUrl.trim();
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getBankCard() {
        return bankCard;
    }

    public void setBankCard(String bankCard) {
        this.bankCard = bankCard == null ? null : bankCard.trim();
    }

    public BigDecimal getTotalPaymentAmount() {
        return totalPaymentAmount;
    }

    public void setTotalPaymentAmount(BigDecimal totalPaymentAmount) {
        this.totalPaymentAmount = totalPaymentAmount;
    }

    public Long getTotalPoints() {
        return totalPoints;
    }

    public void setTotalPoints(Long totalPoints) {
        this.totalPoints = totalPoints;
    }

    public Long getSuperiorId() {
        return superiorId;
    }

    public void setSuperiorId(Long superiorId) {
        this.superiorId = superiorId;
    }

    public BigDecimal getCommission() {
        return commission;
    }

    public void setCommission(BigDecimal commission) {
        this.commission = commission;
    }

    public BigDecimal getFreight() {
        return freight;
    }

    public void setFreight(BigDecimal freight) {
        this.freight = freight;
    }

    public Long getDepositPaid() {
        return depositPaid;
    }

    public void setDepositPaid(Long depositPaid) {
        this.depositPaid = depositPaid;
    }

    public String getPayPassWord() {
        return payPassWord;
    }

    public void setPayPassWord(String payPassWord) {
        this.payPassWord = payPassWord == null ? null : payPassWord.trim();
    }

    public BigDecimal getBalance() {
        return balance;
    }

    public void setBalance(BigDecimal balance) {
        this.balance = balance;
    }

    public BigDecimal getCashRoll() {
        return cashRoll;
    }

    public void setCashRoll(BigDecimal cashRoll) {
        this.cashRoll = cashRoll;
    }

    public Long getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Long createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public Long getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public void setLastUpdatedBy(Long lastUpdatedBy) {
        this.lastUpdatedBy = lastUpdatedBy;
    }

    public Date getLastUpdatedDate() {
        return lastUpdatedDate;
    }

    public void setLastUpdatedDate(Date lastUpdatedDate) {
        this.lastUpdatedDate = lastUpdatedDate;
    }

    public Integer getRemoveFlag() {
        return removeFlag;
    }

    public void setRemoveFlag(Integer removeFlag) {
        this.removeFlag = removeFlag;
    }
}

添加 service 层

package lf.service;

import lf.entity.BsdUser;


public interface BsdUserSerive {
    /**
     * 根据用户id获取用户
     * @param id
     * @return
     */
    public BsdUser getUserById(Long id);
}
package lf.service.impl;

import lf.entity.BsdUser;
import lf.mapper.BsdUserMapper;
import lf.service.BsdUserSerive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class BsdUserSeriveImpl implements BsdUserSerive{

    @Autowired
    private BsdUserMapper userMapper;
    /**
     * 根据用户id获取用户信息
     * @param id
     * @return
     */
    @Override
    public BsdUser getUserById(Long id) {
        return userMapper.getUserById(id);
    }
}

添加 mapper 层

package lf.mapper;

import lf.entity.BsdUser;
import org.mapstruct.Mapper;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

public interface BsdUserMapper{

    /**
     * 根据用户id获取用户信息
     * @param id
     * @return
     */
    public BsdUser getUserById(Long id);

}

添加 mapper 的 xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="lf.mapper.BsdUserMapper">
  <resultMap id="BsdUserResultMap" type="lf.entity.BsdUser">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="org_id" jdbcType="BIGINT" property="orgId" />
    <result column="user_type" jdbcType="INTEGER" property="userType" />
    <result column="code" jdbcType="VARCHAR" property="code" />
    <result column="login_name" jdbcType="VARCHAR" property="loginName" />
    <result column="phone" jdbcType="VARCHAR" property="phone" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="short_name" property="shortName" jdbcType="VARCHAR" />
    <result column="register_attachment_url" property="registerAttachmentUrl" jdbcType="VARCHAR" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="contact_user_name" jdbcType="VARCHAR" property="contactUserName" />
    <result column="address" jdbcType="VARCHAR" property="address" />
    <result column="longitude" jdbcType="DECIMAL" property="longitude" />
    <result column="latitude" jdbcType="DECIMAL" property="latitude" />
    <result column="level" jdbcType="INTEGER" property="level" />
    <result column="img_url" jdbcType="VARCHAR" property="imgUrl" />
    <result column="state" jdbcType="INTEGER" property="state" />
    <result column="bank_card" jdbcType="VARCHAR" property="bankCard" />
    <result column="total_payment_amount" jdbcType="DECIMAL" property="totalPaymentAmount" />
    <result column="commission" jdbcType="DECIMAL" property="commission" />
    <result column="freight" jdbcType="DECIMAL" property="freight" />
    <result column="total_points" jdbcType="BIGINT" property="totalPoints" />
    <result column="superior_id" jdbcType="BIGINT" property="superiorId" />
    <result column="created_by" jdbcType="BIGINT" property="createdBy" />
    <result column="created_date" jdbcType="TIMESTAMP" property="createdDate" />
    <result column="last_updated_by" jdbcType="BIGINT" property="lastUpdatedBy" />
    <result column="last_updated_date" jdbcType="TIMESTAMP" property="lastUpdatedDate" />
    <result column="remove_flag" jdbcType="INTEGER" property="removeFlag" />
    <result column="deposit_paid" jdbcType="DECIMAL" property="depositPaid" />
    <result column="pay_pass_word" jdbcType="VARCHAR" property="payPassWord" />
    <result column="balance" jdbcType="DECIMAL" property="balance" />
    <result column="cash_roll" jdbcType="DECIMAL" property="cashRoll" />
  </resultMap>
  <sql id="BsdUser_Column_List">
    id, org_id, user_type, code, login_name, phone, name,short_name,register_attachment_url,password, contact_user_name,
    address, longitude, latitude, level, img_url, state, bank_card, total_payment_amount,commission,freight,
    total_points, superior_id, created_by, created_date, last_updated_by, last_updated_date, 
    remove_flag, deposit_paid, pay_pass_word, balance, cash_roll
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BsdUserResultMap">
    select
    <include refid="BsdUser_Column_List" />
    from bsd_user
    where id = #{id}
  </select>

  <select id="getUserById" parameterType="java.lang.Long" resultMap="BsdUserResultMap">
    select
    <include refid="BsdUser_Column_List" />
    from bsd_user
    where id = #{id}
  </select>



</mapper>

添加 jsp(如果工具是 idea,jsp 路径如为:/src/main/resources/META-INF/resources/WEB-INF/jsp;如果 eclipse、myEclipse 工具,放在在 src/main 下面创建 webapp/WEB-INF/jsp 目录用来存放我们的 jsp 页面)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>主页</title>
</head>
<body>

    <h1>欢迎登陆甘雨路主页</h1>
    <div>登陆时间:${time}</div>
    <div>登陆人:${loginName}</div>


</body>
</html>

添加 mybatis 配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="Integer" type="java.lang.Integer" />
        <typeAlias alias="Long" type="java.lang.Long" />
        <typeAlias alias="HashMap" type="java.util.HashMap" />
        <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
        <typeAlias alias="ArrayList" type="java.util.ArrayList" />
        <typeAlias alias="LinkedList" type="java.util.LinkedList" />
    </typeAliases>
</configuration>

添加 application.properties 文件(基本配置)

# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp

#swagger
modulePath=/lf

添加 datasource.properties 文件(数据源配置)

#数据源配置
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/bsdmxm?useUnicode=true&characterEncoding=utf8
spring.datasource.username = bs
spring.datasource.password = bs7

添加 mybatis.properties 文件(mybatis 配置)

#mybatis 配置
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:lf/mapper/xml/*.xml
mybatis.type-aliases-package=lf.entity

 然后启动程序,在浏览器输入 http://localhost:8080/swagger-ui.html  可查看相关接口

 然后启动程序,在浏览器输入 http://localhost:8080/lf/page/company?id=52  即可

 

然后启动程序,在浏览器输入 http://localhost:8080/lf/user/info?id=51  即可

 

spring boot整合mybatis+mybatis-plus的示例代码

spring boot整合mybatis+mybatis-plus的示例代码

Spring boot对于我来说是一个刚接触的新东西,学习过程中,发现这东西还是很容易上手的,Spring boot没配置时会默认使用Spring data jpa,这东西可以说一个极简洁的工具,可是我还是比较喜欢用mybatis,工具是没有最好的,只有这合适自己的。

说到mybatis,最近有一个很好用的工具--------mybatis-Plus(官网),现在更新的版本是2.1.2,这里使用的也是这个版本。我比较喜欢的功能是代码生成器,条件构造器,这样就可以更容易的去开发了。

mybatisPlus官网上是有Spring boot整个的例子的,我也跟着它走了一篇,结果,程序没跑起来,后来才知道demo用的H2 database,和MysqL根本不是同一样东西,所以各位想要整合mybatisPlus,可以不看官网的,可以少走弯路。

下面就是整合的过程

1、首先要把需要的jar文件都弄过来,pom.xml需要的东西如下

pom.xml(不完整)

<!-- mybatis-plus begin -->
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatisplus-spring-boot-starter</artifactId>
  <version>1.0.4</version>
</dependency>
<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus</artifactId>
  <version>2.1.2</version>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mybatis-plus end -->

<!-- druid阿里巴巴数据库连接池 -->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.1.3</version>
</dependency>
<!--MysqL-->
<dependency>
  <groupId>MysqL</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.3.1</version>
</dependency>

2、添加mybatis相关的配置,如账号、密码等。这里我使用了application.yml来配。

application.yml

server:
  port: 8080

#spring
spring:
 devtools:
  restart:
   enabled: true   #这里是为了热部署的,与mybatis是无关的

 #DATABASE CONfig
 datasource:
  driver-class-name: com.MysqL.jdbc.Driver
  username: root
  password: root
  url: jdbc:MysqL://MysqLdb:3306/tdx_shop?useUnicode=true&characterEncoding=utf-8
  type: com.alibaba.druid.pool.DruidDataSource  #这里是配置druid连接池,以下都是druid的配置信息
  filters: stat,wall,log4j
  maxActive: 20
  initialSize: 1
  maxWait: 60000
  minIdle: 1
  timeBetweenevictionRunsMillis: 60000
  minevictableIdleTimeMillis: 300000
  validationQuery: select 'x'
  testWhileIdle: true
  testOnBorrow: false
  testOnReturn: false
  poolPreparedStatements: true
  maxOpenPreparedStatements: 20
  connection-properties: druid.stat.merggsql=ture;druid.stat.slowsqlMillis=5000

#mybatis
mybatis:
 mapper-locations: classpath*:/mapper/**Mapper.xml  #把xml文件放在com.XX.mapper.*中可能会出现找到的问题,这里把他放在resource下的mapper中
 #实体扫描,多个package用逗号或者分号分隔
 typeAliasesPackage: com.tdx.account_service.entity #这里是实体类的位置
 configuration:
  map-underscore-to-camel-case: true
  cache-enabled: false
#logging
logging:
 level: warn

配置的东西和我们以前用mybatis配置可以说差不多,但spring boot是没有xml配置文件的。注意一下红字的内容,基本没问题了。

3、mybatis-Plus配置文件------MybatisPlusConfig,首先上图说明一下文件路径。其中MybatisPlusConfig是放在config文件夹内,而xml文件是放在resouces下mapper中。

接着就是MybatisPlusConfig内容部分了

MybatisProperties.java

package com.tdx.account_service.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.plugins.parser.IsqlParser;
import com.baomidou.mybatisplus.plugins.parser.IsqlParserFilter;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantsqlParser;
import com.baomidou.mybatisplus.spring.MybatissqlSessionfactorybean;
import com.baomidou.mybatisplus.spring.boot.starter.SpringBootVFS;
import com.baomidou.mybatisplus.toolkit.PluginUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
import java.sql.sqlException;
import java.util.ArrayList;
import java.util.List;
/**
 * code is far away from bug with the animal protecting
 * ┏┓   ┏┓
 * ┏┛┻━━━┛┻┓
 * ┃       ┃
 * ┃   ━   ┃
 * ┃ ┳┛ ┗┳ ┃
 * ┃       ┃
 * ┃   ┻   ┃
 * ┃       ┃
 * ┗━┓   ┏━┛
 *   ┃   ┃神兽保佑
 *   ┃   ┃代码无BUG!
 *   ┃   ┗━━━┓
 *   ┃       ┣┓
 *   ┃       ┏┛
 *   ┗┓┓┏━┳┓┏┛
 *    ┃┫┫ ┃┫┫
 *    ┗┻┛ ┗┻┛
 *
 *
 * @Description : MybatisPlus配置
 * ---------------------------------
 * @Author : Liang.Guangqing
 * @Date : Create in 2017/9/19 13:54
 */
@Configuration
@EnableConfigurationProperties(MybatisProperties.class)
public class MybatisPlusConfig {
  @Autowired
  private Environment environment;
  private RelaxedPropertyResolver propertyResolver;
  @Autowired
  private DataSource dataSource;
  @Autowired
  private MybatisProperties properties;
  @Autowired
  private ResourceLoader resourceLoader = new DefaultResourceLoader();
  @Autowired(required = false)
  private Interceptor[] interceptors;
  @Autowired(required = false)
  private DatabaseIdProvider databaseIdProvider;

  /**
   * @Description : mybatis-plus sql执行效率插件【生产环境可以关闭】
   * ---------------------------------
   * @Author : Liang.Guangqing
   * @Date : Create in 2017/9/19 13:57
   */
  @Bean
  public PerformanceInterceptor performanceInterceptor() {
    return new PerformanceInterceptor();
  }

  /**
   * 配置DataSource
   * @return
   * @throws sqlException
   */
  @Bean
  public DataSource druidDataSource() throws sqlException {
    this.propertyResolver = new RelaxedPropertyResolver(environment,"spring.datasource.");

    System.out.println("====================注入druid!====================");
    DruidDataSource datasource = new DruidDataSource();
    datasource.setUrl(propertyResolver.getProperty("url"));
    datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
    datasource.setUsername(propertyResolver.getProperty("username"));
    datasource.setPassword(propertyResolver.getProperty("password"));
    datasource.setinitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size")));
    datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle")));
    datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait")));
    datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active")));
    datasource.setMinevictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis")));
    try {
      datasource.setFilters(propertyResolver.getProperty("filters"));
    } catch (sqlException e) {
      e.printstacktrace();
    }
    return datasource;
  }

  /**
   * @Description : mybatis-plus分页插件
   * ---------------------------------
   * @Author : Liang.Guangqing
   * @Date : Create in 2017/9/19 13:59
   */
  @Bean
  public PaginationInterceptor paginationInterceptor() {
    PaginationInterceptor page = new PaginationInterceptor();
    page.setDialectType("MysqL");
    return page;
  }

  /**
   * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定
   * 配置文件和mybatis-boot的配置文件同步
   * @return
   */
  @Bean
  public MybatissqlSessionfactorybean mybatissqlSessionfactorybean() {
    MybatissqlSessionfactorybean mybatisPlus = new MybatissqlSessionfactorybean();
    mybatisPlus.setDataSource(dataSource);
    mybatisPlus.setVfs(SpringBootVFS.class);
    if (StringUtils.hasText(this.properties.getConfigLocation())) {
      mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
    }
    mybatisPlus.setConfiguration(properties.getConfiguration());
    if (!ObjectUtils.isEmpty(this.interceptors)) {
      mybatisPlus.setPlugins(this.interceptors);
    }
    // MP 全局配置,更多内容进入类看注释
    GlobalConfiguration globalConfig = new GlobalConfiguration();
    globalConfig.setDbType(DBType.MysqL.name());
    // ID 策略 AUTO->`0`("数据库ID自增") INPUT->`1`(用户输入ID") ID_WORKER->`2`("全局唯一ID") UUID->`3`("全局唯一ID")
    globalConfig.setIdType(2);
    mybatisPlus.setGlobalConfig(globalConfig);
    MybatisConfiguration mc = new MybatisConfiguration();
    mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
    mybatisPlus.setConfiguration(mc);
    if (this.databaseIdProvider != null) {
      mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
    }
    if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
      mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
    }
    if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
      mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
    }
    if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
      mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
    }
    return mybatisPlus;
  }

  /**
   * 注册一个StatViewServlet
   * @return
   */
  @Bean
  public ServletRegistrationBean DruidStatViewServle(){
    //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
    //添加初始化参数:initParams
    //白名单:
    // servletRegistrationBean.addInitParameter("allow","127.0.0.1");
    //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry,you are not permitted to view this page.
    // servletRegistrationBean.addInitParameter("deny","192.168.1.73");
    //登录查看信息的账号密码.
    servletRegistrationBean.addInitParameter("loginUsername","root");
    servletRegistrationBean.addInitParameter("loginPassword","root");
    //是否能够重置数据.
    servletRegistrationBean.addInitParameter("resetEnable","false");
    return servletRegistrationBean;
  }

  /**
   * 注册一个:filterRegistrationBean
   *
   * @return
   */
  @Bean
  public FilterRegistrationBean druidStatFilter(){
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
    //添加过滤规则.
    filterRegistrationBean.addUrlPatterns("/*");
    //添加不需要忽略的格式信息.
    filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterRegistrationBean;
  }



}

这里是完整的配置文件,需要注意的是引入的包,别引错了!

4、还要开启dao的扫描,很简单,就是在启动文件中添加@MapperScan("com.tdx.account_service.dao*"),如下是完整的

到这里,配置算是完成了,运行一下项目是可以运行起来的。

我觉得Mybatis-Plus最好玩得应该是代码生成器这部分内容,下面是代码生成器的使用过程

pom.xml上要加点东西

<dependency>
  <groupId>org.apache.veLocity</groupId>
  <artifactId>veLocity-engine-core</artifactId>
  <version>2.0</version>
</dependency>

1、代码生成器的配置文件

MybatisPlusConfig.java

/**
 * copyright (c) 2011-2016,hubin (jobob@qq.com).
 * <p>
 * Licensed under the Apache License,Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing,software
 * distributed under the License is distributed on an "AS IS" BASIS,WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.tdx.account_service.generator;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.enums.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.converts.MysqLTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

/**
 *code is far away from bug with the animal protecting
 * ┏┓   ┏┓
 *┏┛┻━━━┛┻┓
 *┃       ┃  
 *┃   ━   ┃
 *┃ ┳┛ ┗┳ ┃
 *┃       ┃
 *┃   ┻   ┃
 *┃       ┃
 *┗━┓   ┏━┛
 *  ┃   ┃神兽保佑
 *  ┃   ┃代码无BUG!
 *  ┃   ┗━━━┓
 *  ┃       ┣┓
 *  ┃       ┏┛
 *  ┗┓┓┏━┳┓┏┛
 *   ┃┫┫ ┃┫┫
 *   ┗┻┛ ┗┻┛
 *  
 *  @Description : MybatisPlus代码生成器
 *  ---------------------------------
 *  @Author : Liang.Guangqing
 *  @Date : Create in 2017/9/19 14:48 
 */
public class MysqLGenerator {
  private static String packageName="account_service";  //文件路径
  private static String authorName="Liang.Guangqing";   //作者
  private static String table="sc_user";         //table名字
  private static String prefix="sc_";           //table前缀
  private static File file = new File(packageName);
  private static String path = file.getAbsolutePath();
  public static void main(String[] args) {
    // 自定义需要填充的字段
    List<TableFill> tableFillList = new ArrayList<>();
    tableFillList.add(new TableFill("ASDD_SS",FieldFill.INSERT_UPDATE));
    // 代码生成器
    AutoGenerator mpg = new AutoGenerator().setGlobalConfig(
        // 全局配置
        new GlobalConfig()
            .setoutputDir(path+"/src/main/java")//输出目录
            .setFileOverride(true)// 是否覆盖文件
            .setActiveRecord(true)// 开启 activeRecord 模式
            .setEnableCache(false)// XML 二级缓存
            .setBaseResultMap(true)// XML ResultMap
            .setBaseColumnList(true)// XML columList
            .setopen(false)//生成后打开文件夹
            .setAuthor(authorName)
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
         .setMapperName("%sMapper")
         .setXmlName("%sMapper")
         .setServiceName("%sService")
         .setServiceImplName("%sServiceImpl")
         .setControllerName("%sController")
    ).setDataSource(
        // 数据源配置
        new DataSourceConfig()
            .setDbType(DbType.MysqL)// 数据库类型
            .setTypeConvert(new MysqLTypeConvert() {
              // 自定义数据库表字段类型转换【可选】
              @Override
              public DbColumnType processtypeConvert(String fieldType) {
                System.out.println("转换类型:" + fieldType);
                // if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
                //  return DbColumnType.BOOLEAN;
                // }
                return super.processtypeConvert(fieldType);
              }
            })
            .setDriverName("com.MysqL.jdbc.Driver")
            .setUsername("root")
            .setPassword("root")
            .setUrl("jdbc:MysqL://127.0.0.1:3306/tdx_shop?characterEncoding=utf8")
    ).setStrategy(
        // 策略配置
        new StrategyConfig()
            // .setCapitalMode(true)// 全局大写命名
            //.setDbColumnUnderline(true)//全局下划线命名
            .setTablePrefix(new String[]{prefix})// 此处可以修改为您的表前缀
            .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
            .setInclude(new String[] { table }) // 需要生成的表
            .setRestControllerStyle(true)
            //.setExclude(new String[]{"test"}) // 排除生成的表
            // 自定义实体父类
            // .setSuperEntityClass("com.baomidou.demo.TestEntity")
            // 自定义实体,公共字段
            //.setSuperEntityColumns(new String[]{"test_id"})
            .setTableFillList(tableFillList)
        // 自定义 mapper 父类
        // .setSuperMapperClass("com.baomidou.demo.TestMapper")
        // 自定义 service 父类
        // .setSuperServiceClass("com.baomidou.demo.TestService")
        // 自定义 service 实现类父类
        // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
        // 自定义 controller 父类
        .setSuperControllerClass("com.tdx."+packageName+".controller.AbstractController")
        // 【实体】是否生成字段常量(默认 false)
        // public static final String ID = "test_id";
        // .setEntityColumnConstant(true)
        // 【实体】是否为构建者模型(默认 false)
        // public User setName(String name) {this.name = name; return this;}
        // .setEntityBuilderModel(true)
        // 【实体】是否为lombok模型(默认 false)<a href="https://projectlombok.org/" rel="external nofollow" >document</a>
        // .setEntityLombokModel(true)
        // Boolean类型字段是否移除is前缀处理
        // .setEntityBooleanColumnRemoveIsPrefix(true)
        // .setRestControllerStyle(true)
        // .setControllerMappingHyphenStyle(true)
    ).setPackageInfo(
        // 包配置
        new PackageConfig()
            //.setModuleName("User")
            .setParent("com.tdx."+packageName)// 自定义包路径
            .setController("controller")// 这里是控制器包名,默认 web
            .setEntity("entity")
            .setMapper("dao")
            .setService("service")
            .setServiceImpl("service.impl")
            //.setXml("mapper")
    ).setCfg(
        // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
        new InjectionConfig() {
          @Override
          public void initMap() {
            Map<String,Object> map = new HashMap<>();
            map.put("abc",this.getConfig().getGlobalConfig().getAuthor() + "-mp");
            this.setMap(map);
          }
        }.setFileOutConfigList(Collections.<FileOutConfig>singletonList(new FileOutConfig("/templates/mapper.xml.vm") {
          // 自定义输出文件目录
          @Override
          public String outputFile(TableInfo tableInfo) {
            return path+"/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
          }
        }))
    ).setTemplate(
        // 关闭默认 xml 生成,调整生成 至 根目录
        new TemplateConfig().setXml(null)
        // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
        // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
        // .setController("...");
        // .setEntity("...");
        // .setMapper("...");
        // .setXml("...");
        // .setService("...");
        // .setServiceImpl("...");
    );

    // 执行生成
    mpg.execute();

    // 打印注入设置,这里演示模板里面怎么获取注入内容【可无】
    System.err.println(mpg.getCfg().getMap().get("abc"));
  }
}

文件中修改的内容还是很多的,最主要的还是MysqL的连接信息,没理由你账号,密码都错了还能连得上吧,其次设置一下你生成的模板文件路径,我这里生成的路径在上面图可以看得到,是在com.tdx.account_service下的,注意,xml文件要放在resources下,不然是识别的,说找不到这个方法

按照官网的代码模板生成的文件基本是白白的,主要是mybatis-Plus集成了公共方法,很多常用的工具都可以引用了。在这里我提供一下我修改后Controller.java.vm文件,主要还是按照我自己的习惯去弄的

controller.java.vm

package ${package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClasspackage})
import ${superControllerClasspackage};
#end
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.common.DatatablesJSON;
import ${package.Entity}.common.JSONResult;
import ${package.Entity}.${entity};
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *code is far away from bug with the animal protecting
 * ┏┓   ┏┓
 *┏┛┻━━━┛┻┓
 *┃       ┃  
 *┃   ━   ┃
 *┃ ┳┛ ┗┳ ┃
 *┃       ┃
 *┃   ┻   ┃
 *┃       ┃
 *┗━┓   ┏━┛
 *  ┃   ┃神兽保佑
 *  ┃   ┃代码无BUG!
 *  ┃   ┗━━━┓
 *  ┃       ┣┓
 *  ┃       ┏┛
 *  ┗┓┓┏━┳┓┏┛
 *   ┃┫┫ ┃┫┫
 *   ┗┻┛ ┗┻┛
 *  
 *  @description : ${entity} 控制器
 *  ---------------------------------
 *   @author ${author}
 *  @since ${date}
 */
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
  private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);
  @Autowired
  public ${table.serviceName} ${table.entityPath}Service;

  /**
   * @description : 获取分页列表
   * ---------------------------------
   * @author : ${author}
   * @since : Create in ${date}
   */
  @RequestMapping(value = "/get${entity}List",method = RequestMethod.POST)
  public Object get${entity}List(${entity} param,@RequestParam(value = "draw",defaultValue = "0") Integer draw,@RequestParam(value = "length") Integer length,@RequestParam(value = "start") Integer start) {
      DatatablesJSON<${entity}> resJson=new DatatablesJSON<>();
      try {
        Integer pageNo=getPageNo(start,length);
        Page<${entity}> page=new Page<${entity}>(pageNo,length);
        ${table.entityPath}Service.selectPage(page,new EntityWrapper<${entity}>(param));
        resJson.setDraw(draw++);
        resJson.setRecordsTotal(page.getTotal());
        resJson.setRecordsFiltered(page.getTotal());
        resJson.setData(page.getRecords());
        resJson.setSuccess(true);
      }catch (Exception e){
        resJson.setSuccess(false);
        resJson.setError("异常信息:{"+e.getClass().getName()+"}");
        logger.info("异常信息:{}"+e.getMessage());
      }
      return resJson;
  }

  /**
   * @description : 通过id获取${entity}
   * ---------------------------------
   * @author : ${author}
   * @since : Create in ${date}
   */
  @RequestMapping(value = "/get${entity}ById",method = RequestMethod.GET)
  public Object get${entity}ById(String id) {
      JSONResult<${entity}> resJson = new JSONResult<>();
      try {
        ${entity} param= ${table.entityPath}Service.selectById(id);
        resJson.setData(param);
        resJson.setSuccess(true);
      }catch (Exception e) {
        resJson.setSuccess(false);
        resJson.setMessage("异常信息:{"+e.getClass().getName()+"}");
        logger.info("异常信息:{}"+e.getMessage());
      }
      return resJson;
  }

  /**
   * @description : 通过id删除${entity}
   * ---------------------------------
   * @author : ${author}
   * @since : Create in ${date}
   */
  @RequestMapping(value = "/delete${entity}ById",method = RequestMethod.GET)
  public Object delete${entity}ById(String id) {
      JSONResult<${entity}> resJson = new JSONResult<>();
      try{
        resJson.setSuccess(${table.entityPath}Service.deleteById(id));
      }catch (Exception e) {
        resJson.setSuccess(false);
        resJson.setMessage("异常信息:{"+e.getClass().getName()+"}");
        logger.info("异常信息:{}"+e.getMessage());
      }
      return resJson;
  }

  /**
   * @description : 通过id更新${entity}
   * ---------------------------------
   * @author : ${author}
   * @since : Create in ${date}
   */
  @RequestMapping(value = "/update${entity}ById",method = RequestMethod.POST)
  public Object update${entity}ById(${entity} param) {
      JSONResult<${entity}> resJson = new JSONResult<>();
      try{
        resJson.setSuccess(${table.entityPath}Service.updateById(param));
      }catch (Exception e) {
        resJson.setSuccess(false);
        resJson.setMessage("异常信息:{"+e.getClass().getName()+"}");
        logger.info("异常信息:{}"+e.getMessage());
      }
      return resJson;
  }

  /**
   * @description : 添加${entity}
   * ---------------------------------
   * @author : ${author}
   * @since : Create in ${date}
   */
  @RequestMapping(value = "/add${entity}",method = RequestMethod.POST)
  public Object add${entity}(${entity} param) {
      JSONResult<${entity}> resJson = new JSONResult<>();
      try{
        resJson.setSuccess(${table.entityPath}Service.insert(param));
      }catch (Exception e) {
        resJson.setSuccess(false);
        resJson.setMessage("异常信息:{"+e.getClass().getName()+"}");
        logger.info("异常信息:{}"+e.getMessage());
      }
      return resJson;
  }
}

除了这个文件,其他代码模板我都是按照官网那样的,这里引用3个外部的文件,有AbstractController.java(控制器基类)、DatatablesJSON.java和JSONResult.java,然后这些文件又引用了其他文件,我懵逼了,怎么文件这么多啊,看来如果全部都贴上来得多占地方啊,所以我选择相信码云,如果需要请在码云上按照少的文件下载,码云地址。需要注意的是,我的模板是直接代替了mybatis-plus.jar中的templates目录。

最后就到了测试过程

下面的代码段都是放在Controller文件里面,然后启动程序,对应端口,请求方法。测试的话是需要按照自己的实体类操作的,所以仅供参考。

  /**
   * 分页 PAGE
   */
  @GetMapping("/test")
  public Page<User> test() {
    return userService.selectPage(new Page<User>(0,12));
  }

  /**
   * AR 部分测试
   */
  @GetMapping("/test1")
  public Page<User> test1() {
    User user = new User();
    System.err.println("删除所有:" + user.delete(null));
    //user.setId(2017091801L);
    user.setAccout("test"+num++);
    user.setType("test");
    user.setCreateTime(new Date());
    user.setPhone("13111110000");
    user.setPassword("123456");
    user.setNickname("guangqing"+2*num++);
    user.insert();
    System.err.println("查询插入结果:" + user.selectById().toString());
    //user.setNickname("mybatis-plus-ar");
    System.err.println("更新:" + user.updateById());
    return user.selectPage(new Page<User>(0,12),null);
  }

  /**
   * 增删改查 CRUD
   */
  @GetMapping("/test2")
  public User test2() {
    User user = new User();
    user.setId(123456L);
    user.setAccout("test");
    user.setType("test");
    user.setCreateTime(new Date());
    user.setPhone("13111110000");
    user.setPassword("123456");
    user.setNickname("guangqing");
    System.err.println("删除一条数据:" + userService.deleteById(1L));
    System.err.println("插入一条数据:" + userService.insert(user));
    User user2 = new User();
    user.setId(223456L);
    user.setAccout("test2");
    user.setType("test");
    user.setCreateTime(new Date());
    user.setPhone("13111110000");
    user.setPassword("123456");
    user.setNickname("guangqing");
    boolean result = userService.insert(user);
    // 自动回写的ID
    Long id = user.getId();
    System.err.println("插入一条数据:" + result + ",插入信息:" + user.toString());
    System.err.println("查询:" + userService.selectById(id).toString());
    Page<User> userListPage = userService.selectPage(new Page<User>(1,5),new EntityWrapper<>(new User()));
    System.err.println("total=" + userListPage.getTotal() + ",current list size=" + userListPage.getRecords().size());
    return userService.selectById(1L);
  }

  @GetMapping("testSelect")
  public Object testSelect() {
    Integer start = 0;
    Integer length =10;
    User param = new User();
    //param.setNickname("guangqing2");
    Integer pageNo=getPageNo(start,length);
    Page<User> page =new Page<User>(pageNo,length);
    EntityWrapper<User> ew = new EntityWrapper<User>();
    ew.setEntity(param);
    ew.where("password={0}","123456")
        .like("nickname","guangqing")
        .ge("create_time","2017-09-21 15:50:00");
    userService.selectPage(page,ew);
    DatatablesJSON<User> resJson= new DatatablesJSON<>();
    //resJson.setDraw(draw++);
    resJson.setRecordsTotal(page.getTotal());
    resJson.setRecordsFiltered(page.getTotal());
    resJson.setData(page.getRecords());
    return resJson;
  }


  @GetMapping("/selectsql")
  public Object getUserBysql() {
    JSONObject result = new JSONObject();
    result.put("records",userService.selectListBysql());
    return result;
  }

  /**
   * 7、分页 size 一页显示数量 current 当前页码
   * 方式一:http://localhost:8080/user/page?size=1¤t=1<br>
   * 方式二:http://localhost:8080/user/pageHelper?size=1¤t=1<br>
   */

  // 参数模式分页
  @GetMapping("/page")
  public Object page(Page page) {
    return userService.selectPage(page);
  }

  // ThreadLocal 模式分页
  @GetMapping("/pageHelper")
  public Object pageHelper(Page page) {
    pageHelper.setPagination(page);
    page.setRecords(userService.selectList(null));
    page.setTotal(pageHelper.freetotal());//获取总数并释放资源 也可以 pageHelper.getTotal()
    return page;
  }


  /**
   * 测试事物
   * http://localhost:8080/user/test_transactional<br>
   * 访问如下并未发现插入数据说明事物可靠!!<br>
   * http://localhost:8080/user/test<br>
   * <br>
   * 启动 Application 加上 @EnableTransactionManagement 注解其实可无默认貌似就开启了<br>
   * 需要事物的方法加上 @Transactional 必须的哦!!
   */
  @Transactional
  @GetMapping("/test_transactional")
  public void testTransactional() {
    //userService.insert(new User(1000L,"测试事物",16,3));
    System.out.println(" 这里手动抛出异常,自动回滚数据");
    throw new RuntimeException();
  }

这么多的测试,我觉得最有趣的是条件构造器,在官网上有更齐全的,而我这里是按照我自己的需求写的。

最后谢谢大家的观看,写博客经验不足,写得不好请见谅,如果能给你带来帮助请点个赞,若遇到不明白的,或者我有写错的地方请提出,谢谢!也希望大家多多支持编程小技巧。

您可能感兴趣的文章:

  • 详解Spring boot上配置与使用mybatis plus
  • SpringBoot Mybatis Plus公共字段自动填充功能

spring boot整合mybatis-plus

spring boot整合mybatis-plus

1 MyBatis-plus 介绍

MyBatis- plus是MyBatis的一个功能强大的增强工具包,用于简化开发。该工具包为MyBatis提供了一些高效、有用、开箱即用的特性,使用它可以有效地节省开发时间。

1.1 优势

  1. MyBatis-plus 提供基础增删改查、分页查询等接口,能够有效简化开发,提升开发效率。尤其是后台管理系统、运营系统等场景,特别适合使用MyBatis-plus进行开发。
  2. 自带的代码生成器也很好用,可以生成器可以快速生成Mapper.java、Mapper.xml、dao、service、controller层代码。
  3. 支持多种数据库:支持 mysql,oracle,db2,h2,hsql,sqlite,postgresql,sqlserver,Phoenix,Gauss ,clickhouse,Sybase,OceanBase,Firebird,cubrid,goldilocks,csiidb 等多种数据库

2 spring-boot 整合 MyBatis-plus

2.1 导入pom依赖

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

<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>8.0.17</version>
</dependency>

PS:可以自行修改版本。

2.2 配置数据库yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    type: com.alibaba.druid.pool.DruidDataSource

# Logger Config
logging:
  level:
    com.baomidou.mybatisplus.samples: debug

2.3 增加config文件

@Configuration
@MapperScan("com.prepared.mapper")
public class MybatisPlusConfig {

}

PS: 如果需要分页,需要增加分页配置

    // 旧版
//    @Bean
//    public PaginationInterceptor paginationInterceptor() {
//        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
//        // paginationInterceptor.setOverflow(false);
//        // 设置最大单页限制数量,默认 500 条,-1 不受限制
//        // paginationInterceptor.setLimit(500);
//        // 开启 count 的 join 优化,只针对部分 left join
//        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
//        return paginationInterceptor;
//    }
    
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
    return interceptor;
}

2.4 集成代码生成器

导入pom包

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>mybatis-plus-generator</artifactId>
  <version>3.4.1</version>
</dependency>
<dependency>
  <groupId>org.freemarker</groupId>
  <artifactId>freemarker</artifactId>
  <version>2.3.28</version>
</dependency>

代码生成类

package com.prepared;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
//        String projectPath = System.getProperty("user.dir");
        String projectPath = "/Users/shibo_zhong/Documents/workspace-prepared/spring-boot-learning/spring-boot-mybatis-plus";
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("prepared");
        gc.setOpen(true);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("com");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("tuser").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

执行main方法,按照提示输入即可生成代码

请输入模块名:
prepared
请输入tuser:
tuser

生成代码如下所示:

3 验证

编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisPlusApplicationTests {

    @Resource
    private TuserMapper tuserMapper;

    @Test
    public void testAddUser() {
        Tuser tuser = new Tuser();
        tuser.setAge(1);
        tuser.setIdCard("123415413");
        tuser.setIsmale(Boolean.TRUE);
        tuser.setName("prepared");
        tuserMapper.insert(tuser);
    }
}

整合完成!

github开源地址

api文档

本文涉及代码地址

关于Spring Boot整合Mybatis Plus和Swagger2的教程详解springboot整合mybatis-plus的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于sprigboot整合mybatis-plus、Spring boot 、mybatis 和 swagger 整合、spring boot整合mybatis+mybatis-plus的示例代码、spring boot整合mybatis-plus等相关内容,可以在本站寻找。

本文标签: