提示:这里可以添加本文要记录的大概内容:
1、是一款让你更好的书写API文档规范且完整的框架。
2、提供描述、生产、消费和可视化RESTful Web Service。
3、是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面。
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
package com.tzw.config;
import io.swagger.annotations.ApiOperation;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* @author tzw
* @version 1.0
*/
@Configuration
public class Swagger3Config {
@Bean
public Docket apiConfig(){
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
//设置通过什么方式定位到需要生成文档的接口.
// 定位了方法上的Api0peration
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())//接口URL路径,any表示全部的路径
.build();
}
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("第一个Springboot项目")
.description("项目描述信息")
.contact(new Contact("tzw","https://blog.csdn.net/qq_45821255?spm=1011.2415.3001.5343","[email protected]"))
.version("1.0")
.build();
}
}
package com.tzw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import springfox.documentation.oas.annotations.EnableOpenApi;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableOpenApi//以后很多配置都需要在启动类上加上Enable...,表示打开。
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
@Api(tags = {“xxx”})用在类上,表示说明该类的作用。
@RestController
@RequestMapping("/test")
@Api(tags = {"第一个spring项目测试模块"})//用在类上,表示说明该类的作用。
public class TestController {
}
为了测试,完善一下controller层,同时完善pojo层:
controller:
@RestController
@RequestMapping("/test")
@Api(tags = {"第一个spring项目测试模块"})//用在类上,表示说明该类的作用。
public class TestController {
@GetMapping()
@ApiOperation(value = "显示测试结果")//用在方法上,说明方法的用途和作用
public Object testDemo(){
List<TestDay01> list = new ArrayList<>();
list.add(new TestDay01("张三",18));
list.add(new TestDay01("张三1",12));
list.add(new TestDay01("张三2",13));
return list;
}
}
代码:
package com.tzw.gene.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tzw.gene.entity.User;
import com.tzw.gene.service.IUserService;
import com.tzw.gene.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
/**
*
* 前端控制器
*
*
* @author student_tzw
* @since 2022-08-22
*/
@RestController
@RequestMapping("/gene/user")
@Api(tags = "用户管理")
public class UserController {
@Resource
private IUserService service;
@ApiOperation(value = "查询全部数据",httpMethod = "GET")
@GetMapping
public Result select(){
List<User> list = service.testSelect();
return Result.success().setData("list",list);//下面三行代码可以替换此行
// HashMap map = new HashMap<>();
// map.put("list",list);
// return Result.success().setData(map);
}
@ApiOperation("按ID查询")
@GetMapping("/{id}")
public Result selectById(@PathVariable Integer id){
User user = service.getById(id);
return Result.success().setData("user",user);
}
@ApiOperation("分页查询")//需要加入插件
@GetMapping("/{current}/{size}")
public Result selectPage(@PathVariable Integer current,@PathVariable Integer size){
Page<User> page = new Page<>(current, size);
service.page(page);
return Result.success().setData("page",page);
}
@ApiOperation(value = "保存用户",httpMethod = "POST")
@PostMapping
public Result save(@RequestBody User user){
return service.save(user)?Result.success():Result.error();
}
@ApiOperation(value = "更新用户",httpMethod = "PUT")
@PutMapping
public Result update(@RequestBody User user){
return service.updateById(user)?Result.success():Result.error();
}
@ApiOperation(value = "删除用户",httpMethod = "DELETE")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
return service.removeById(id)?Result.success():Result.error();
}
}
pojo代码:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TestDay01 {
private String name;
private int age;
}
@ApiImplicitParams(
@ApiImplicitParam(
name = "id",value = "测试id",required = true,
paramType = "path",
dataType = "Integer", dataTypeClass = Integer.class
)
)
访问地址:http://localhost:8080/swagger-ui/index.html
在controller里加一个查询模块:(为方法(增删查改)中的形参做说明)
@GetMapping("/find")
@ApiOperation(value = "按给定id来查询信息")//用在方法上,说明方法的用途和作用
@ApiImplicitParams(
@ApiImplicitParam(
name = "id",value = "测试id",required = true,
paramType = "path",
dataType = "Integer", dataTypeClass = Integer.class
)
)
public Object selectById(@PathVariable int id){
return new TestDay01("张三",18);
}
在pom.xml中配置即可
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
创建springboot模块的时候可以选择(lombok、apache模板引擎、热部署和驱动,SpringWeb等…)
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.tzwgroupId>
<artifactId>first_boot_projectartifactId>
<version>0.0.1-SNAPSHOTversion>
<properties>
<java.version>1.8java.version>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASEspring-boot.version>
properties>
<dependencies>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-boot-starterartifactId>
<version>3.0.0version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.5.1version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-freemarkerartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aspectsartifactId>
<version>5.2.5.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.1.4version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-dependenciesartifactId>
<version>${spring-boot.version}version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.1version>
<configuration>
<source>1.8source>
<target>1.8target>
<encoding>UTF-8encoding>
configuration>
plugin>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<version>2.3.7.RELEASEversion>
<configuration>
<mainClass>com.tzw.TestApplicationmainClass>
configuration>
<executions>
<execution>
<id>repackageid>
<goals>
<goal>repackagegoal>
goals>
execution>
executions>
plugin>
plugins>
build>
project>
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
datasource:
url: jdbc:mysql://localhost:3306/mybatis?serverTimeZone=GMT%2B8
username: root
password: admin
我们可以在applicationTest里面配置,代码从baomidou.com的快速入门中获得
package com.tzw;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AppTests {
@Test
void contextLoads() {
}
@Test
public void generator(){
FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis?serverTimeZone=UTC", "root", "admin")
.globalConfig(builder -> {
builder.author("student_tzw") // 设置作者
.enableSwagger() // 开启 swagger 模式, 开启之后,在实体类中有api的注解
.fileOverride() // 覆盖已生成文件
.outputDir(".\\src\\main\\java"); // 指定输出目录(在当前目录的java目录下)
})
.packageConfig(builder -> {
builder.parent("com.tzw") // 设置父包名
.moduleName("gene") ;// 设置父包模块名
//.pathInfo(Collections.singletonMap(OutputFile.xml, "D://")); // 设置mapperXml生成路径
//默认有生成路径,可以不配置
})
.strategyConfig(builder -> {
builder.addInclude("tb_user") // 设置需要生成的表名,多个表时,在后面添加即可。
.addTablePrefix("tb_") // 设置过滤表前缀,多个前缀时,在后面添加即可。
.entityBuilder().enableLombok()//开启lombok
.controllerBuilder().enableRestStyle();//开启restController
// .enableChainModel()//开启链式编程
// .logicDeletePropertyName()
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
Result类:
package com.tzw.gene.util;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.HashMap;
import java.util.Map;
/**
* @author tzw
* @version 1.0
* 返回结果
*/
@Data
@Accessors(chain = true)
public class Result {
//操作是否成功
private Boolean isSuccess;
//状态码
private Integer code;
//消息
private String message;
//返回操作数据
private Map<String,Object> data;
public static Result success(){
return new Result().setIsSuccess(true)
.setCode(ResultCode.SUCCESS)
.setMessage("操作成功")
.setData(new HashMap<>());
}
public static Result error(){
return new Result().setIsSuccess(false)
.setCode(ResultCode.ERROR)
.setMessage("操作失败")
.setData(new HashMap<>());
}
public Result setData(HashMap<String,Object> data){
this.data = data;
return this;
}
public Result setData(String key,Object value){
this.data.put(key, value);
return this;
}
}
ResultCode状态码接口
package com.tzw.gene.util;
/**
* @author tzw
* @version 1.0
*/
public interface ResultCode {
Integer SUCCESS = 20000;//表示成功
Integer ERROR = 20001;//表示失败
}
Entity、mapper、service层全部都自动生成,我们只需要加我们需要的插件及配置。
Controller层的增删查改:
package com.tzw.gene.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tzw.gene.entity.User;
import com.tzw.gene.service.IUserService;
import com.tzw.gene.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
/**
*
* 前端控制器
*
*
* @author student_tzw
* @since 2022-08-22
*/
@RestController
@RequestMapping("/gene/user")
@Api(tags = "用户管理")
public class UserController {
@Resource
private IUserService service;
@ApiOperation("查询全部数据")
@GetMapping
public Result select(){
List<User> list = service.list();
return Result.success().setData("list",list);//下面三行代码可以替换此行
// HashMap map = new HashMap<>();
// map.put("list",list);
// return Result.success().setData(map);
}
@ApiOperation("按ID查询")
@GetMapping("/{id}")
public Result selectById(@PathVariable Integer id){
User user = service.getById(id);
return Result.success().setData("user",user);
}
@ApiOperation("分页查询")//需要加入插件
@GetMapping("/{current}/{size}")
public Result selectPage(@PathVariable Integer current,@PathVariable Integer size){
Page<User> page = new Page<>(current, size);
service.page(page);
return Result.success().setData("page",page);
}
@ApiOperation("保存用户")
@PostMapping
public Result save(@RequestBody User user){
return service.save(user)?Result.success():Result.error();
}
@ApiOperation("更新用户")
@PutMapping
public Result update(@RequestBody User user){
return service.updateById(user)?Result.success():Result.error();
}
@ApiOperation("删除用户")
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id){
return service.removeById(id)?Result.success():Result.error();
}
}
1、在yml中配置mapper的地址和别名
mybatis-plus:
mapper-locations: mapper/**/*.xml
type-aliases-package: com.tzw.gene.entity
2、在包配置的参数中加上要生成mapper.xml的目录
.
.
.
.packageConfig(builder -> {
builder.parent("com.tzw") // 设置父包名
.moduleName("gene") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.xml,".\\src\\resources\\mapper"));