Springboot整合mybatisPlus+Swagger3.0

张春  金牌会员 | 2022-8-29 05:13:39 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 906|帖子 906|积分 2718

SpringBoot+Mybatisplus+Mybatis+Swagger+代码自动生成+log4j

1. SpringBoot+Mybatis+MybatisPlus

1.1 mybatisplus依赖+mybatis依赖
  1.         <dependency>
  2.             <groupId>com.baomidou</groupId>
  3.             <artifactId>mybatis-plus-boot-starter</artifactId>
  4.             <version>3.5.1</version>
  5.         </dependency>
复制代码
  1.     <dependency>
  2.         <groupId>org.mybatis.spring.boot</groupId>
  3.         <artifactId>mybatis-spring-boot-starter</artifactId>
  4.         <version>2.2.2</version>
  5.     </dependency>
复制代码
1.2 配置信息

1.2.1 yml中datasource配置
  1. spring:
  2.   datasource:
  3.     driver-class-name: com.mysql.cj.jdbc.Driver
  4.     url: jdbc:mysql://localhost:3307/community
  5.     username: root
  6.     password: 123456
复制代码

1.2.2 mybatis别名和xml扫描
  1. mybatis:
  2.     mapper-locations: classpath:mappers/*xml
  3.     type-aliases-package: com.zjw.swager.mybatis.entity
复制代码
1.3测试准备

1.3.1编写类Building
  1. public class Building {
  2.   //TypeId是指定这个属性为id,写上这个才可以通过操作数据库中的id属性,否则类似selectById会失效
  3.   //并在后面追加类型,此处写的是自动类型
  4.   @TableId(type = IdType.AUTO)
  5.   private long id;
  6.   private String numbers;
  7.   private String uints;
  8.   private String remarks;
  9.   }
复制代码
1.3.2编写Mapper接口BuildingMapper
  1. @Mapper
  2. public interface BuildingMapper extends BaseMapper<Building> {
  3. }
复制代码
//需要继承BaseMapper,要加上需要操作的泛型
1.3.3 在springboot启动类中添加注解扫描Mapper
  1. @SpringBootApplication
  2. //扫描Mapper包下的Mapper接口
  3. @MapperScan("com.zjw.mapper")
  4. public class Springboottest01Application {
  5.     public static void main(String[] args) {
  6.         SpringApplication.run(Springboottest01Application.class, args);
  7.     }
  8. }
复制代码
1.3.4 编写测试类
  1. @SpringBootTest
  2. public class demo1 {
  3.     @Autowired
  4.     private BuildingMapper buildingMapper;
  5.     @Test
  6.     public void test01(){
  7.         Building building = buildingMapper.selectById(1);
  8.         System.out.println("building = " + building);
  9.     }
  10. }
复制代码
输出结果:
building = Building{id=1, numbers='21栋', uints='1单元', remarks='无'}
测试成功!
1.4 QueryWrapper条件构造器
  1. // 条件查询
  2.         QueryWrapper<Building> queryWrapper = new QueryWrapper<>();
  3.         // eq  参数1 给的是表的字段   参2 值
  4. //        queryWrapper.eq("sid",4);
  5. //        queryWrapper.eq("sage",40);
  6.         // queryWrapper 支持链式编程
  7.         queryWrapper.eq("sid", 4)
  8.                 .eq("sage", 40);
  9.         // 条件包装类 会自动完成  sql的条件 拼接
  10.         // SELECT sid,s_name,sage,ssex,sphone FROM t_student WHERE (sid = ? AND sage = ?)
  11.         Building building = buildingMapper.selectOne(queryWrapper);
  12.         System.out.println("building = " + building);
复制代码

复杂的查询条件时使用QueryWrapper条件构造器
1.5 小结 整合步骤

01 添加mybatis-plus的依赖
02 配置数据库连接要素
03 写自己的mapper 继承 mp 的BaseMapper \ 要给泛型
04 需要在启动类中扫描mapper包
1.6 分页

新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
因此需要添加MybatisPlusConfig配置类进行设置
1.6.1 添加配置类,设置拦截器

@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
// 拦截器添加分页插件
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return mybatisPlusInterceptor;
}
}
1.6.2 测试分页
  1. @Test
  2. public void test02(){
  3.     QueryWrapper<Building> qr = new QueryWrapper<>();
  4.     qr.lt("id",100);
  5.     IPage<Building> page1 = new Page<>(1,4);
  6.     IPage<Building> page = buildingMapper.selectPage(page1, qr);
  7.     System.out.println("page = " + page.getRecords());
  8. }
复制代码
输出结果:
page = [Building{id=1, numbers='21栋', uints='1单元', remarks='无'}, Building{id=7, numbers='17栋', uints='2单元', remar。。。。。。
测试成功!
2. pringBoot+Mybatisplus+Mybatis+Swagger

2.1依赖
  1.         <dependency>
  2.             <groupId>com.baomidou</groupId>
  3.             <artifactId>mybatis-plus-boot-starter</artifactId>
  4.             <version>3.5.1</version>
  5.         </dependency>          org.mybatis.spring.boot        mybatis-spring-boot-starter        2.2.2                        io.springfox        springfox-swagger-ui        2.9.2                    io.springfox        springfox-swagger2        2.9.2   
复制代码
这里的swagger版本建议用低一些的版本,高版本有兼容性问题!
Failed to start bean ‘documentationPluginsBootstrapper’ 把springboot 版本改成2.6.0 以下版本就可以
若有版本问题:
将依赖改成依赖集合
  1.     <dependency>
  2.         <groupId>io.springfox</groupId>
  3.         <artifactId>springfox-boot-starter</artifactId>
  4.         <version>3.0.0</version>
  5.     </dependency>
复制代码
​    原先的Swagger的两个依赖不再需要
​    同时配置中的@EnableSwagger2也不再需要加上,以下为可选项
​    //@EnableSwagger2
​    @EnableOpenApi//可以不写
2.2 配置

swagger需要配置类设置API文档信息
2.2.1编写swagger配置类
  1. //1. 配置类
  2. @Configuration
  3. //2. 开启swagger支持
  4. //@EnableSwagger2
  5. @EnableOpenApi//swagger3.0依赖 可以不写
  6. public class SwaggerApp {
  7.     /**
  8.      * 3、自动创建Docket文档摘要对象
  9.      */
  10.     @Bean
  11.     public Docket createRestApi(){
  12.         return new Docket(DocumentationType.SWAGGER_2) // 选择swagger的版本,这里若选的3.0则要用OAS_30
  13.                 // 配置文档信息:swagger文档的标题、版本、描述
  14.                 .apiInfo(this.apiInfo())
  15.                 .select()
  16.                 // 配置要生成swagger文档的扫描的目录包
  17.                 .apis(RequestHandlerSelectors.basePackage("com.woniu.web"))
  18.                 // 对指定路径下的任意类生成文档
  19.                 .paths(PathSelectors.any())
  20.                 // 创建对象
  21.                 .build();
  22.     }
  23.     private ApiInfo apiInfo(){
  24.         return new ApiInfoBuilder()
  25.                 // 指定文档标题 (在swagger页面会显示)
  26.                 .title("SpringBoot中使用Swagger构建接口文件")
  27.                 // 指定文档的版本
  28.                 .version("1.0")
  29.                 // 文档描述
  30.                 .description("API描述").build();
  31.     }
  32. }
复制代码
2.2.2 通过注解添加API中的内容

2.2.2.1 实体类中
  1. //实体类上的注解
  2. @ApiModel(description = "建筑类实体")
  3. public class Building {
  4.     //TypeId是指定这个属性为id,写上这个才可以通过操作数据库中的id属性,否则类似selectById会失效
  5.     //并在后面追加类型,此处写的是自动类型
  6.   @TableId(type = IdType.AUTO)
  7.   //实体类中属性的注解
  8.   @ApiModelProperty("主键id")
  9.   private long id;
  10.   @ApiModelProperty("楼栋号")
  11.   private String numbers;
  12.   @ApiModelProperty("单元号")
  13.   private String uints;
  14.   @ApiModelProperty("备注")
  15.   private String remarks;
复制代码
2.2.2.2 mapper中的设置
  1. @Mapper
  2. public interface BuildingMapper extends BaseMapper<Building> {
  3. }
复制代码
需要继承BaseMapper ,设置好泛型
2.2.2.3 service中的设置
  1. public interface BuildingService extends IService<Building> {
  2. }
复制代码
需要继承IService
2.2.2.4ServiceImp中的设置
  1. @Service
  2. public class BuildingServiceImpl extends ServiceImpl<BuildingMapper, Building> implements BuildingService {
  3. }
复制代码
在实现BuildingService的同时,还要继承ServiceImpl
2.2.2.5controller 中的设置及注解
  1. @RestController//rest风格注解,替代@Controller和@ResponseBody
  2. @RequestMapping("/building") 设置访问路径
  3. @Api(tags = "楼栋管理")//swagger注解,解释controller的功能
  4. public class BuildingController {
  5.     @Autowired//自动注入
  6.     private BuildingService buildingService;
  7.     @GetMapping
  8.    
  9. public void selectAllBuilding(){
  10.     List<Building> list = buildingService.list();
  11.     System.out.println("list = " + list);
  12. }
  13. }
复制代码
swagger3.0访问路径:http://localhost:8080/swagger-ui/
swagger2访问路径:http://localhost:8080/swagger-ui.html
3. 整合代码自动生成(代码生成器)

3.1 依赖
  1. <dependency>
  2.     <groupId>com.baomidou</groupId>
  3.     <artifactId>mybatis-plus-generator</artifactId>
  4.     <version>3.5.2</version>
  5. </dependency>
  6. <dependency>
  7.       <groupId>mysql</groupId>
  8.       <artifactId>mysql-connector-java</artifactId>
  9. </dependency>
  10. <dependency>
  11.      <groupId>org.springframework.boot</groupId>
  12.      <artifactId>spring-boot-starter-freemarker</artifactId>
  13. </dependency>
复制代码
当前包未传递依赖 MP 包,需要自己引入!
3.2 配置代码生成
  1. public static void main(String[] args) {
  2.         FastAutoGenerator.create(
  3.                 "jdbc:mysql://localhost:3306/spring_db",
  4.                 "root",
  5.                 "root")
  6.                 // 全局配置
  7.                 .globalConfig(builder -> {
  8.                     builder.author("yellow Docter") // 设置作者
  9.                             .enableSwagger() // 开启 swagger 模式
  10.                             .outputDir("C:\\java_lesson\\pro\\springboot_auto\\src\\main\\java"); // 指定输出目录
  11.                 })
  12.                // 包配置
  13.                 .packageConfig(builder -> {
  14.                     builder.parent("com.wn") // 设置父包名
  15.                             .controller("controller") //controller
  16.                             .service("service")       //service
  17.                             .serviceImpl("service.impl")
  18.                             .mapper("mapper")
  19.                             .xml("mapper")
  20.                             .entity("entity");
  21.                 })
  22.                 //表的配置
  23.                 .strategyConfig(builder -> {
  24.                     builder.addInclude("user"); // 设置需要生成的表名
  25.                 })
  26.                 .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
  27.                 .execute();
  28.                  System.out.println("成功了...");
  29.     }
复制代码
3.3运行

配置好生成代码类后直接运行类中主方法
即可生成
注意设置包名及路径

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

张春

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表