美文网首页
SpringBoot整合JPA与Swagger

SpringBoot整合JPA与Swagger

作者: 拼搏男孩 | 来源:发表于2020-04-10 22:51 被阅读0次

    1、整合JPA

    之前我们学习过SpringMVC整合JPA,今天来尝试一下SpringBoot整合JPA

    1.1 添加依赖

    和之前配置thymeleaf一样,可以在创建SpringBoot项目时选择JPA的依赖,也可以在创建项目后手动添加依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    

    只需要添加这一个依赖

    1.2 修改配置文件

    application.yml

    server:
      port: 8081
    spring:
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/mydb?useSSL=true&serverTimezone=UTC&characterEncoding=UTF-8
        password: huwenlong
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: root
      jpa:
        database: mysql
        show-sql: true
        properties:
          hibernate:
            format_sql: true
        hibernate:
          ddl-auto: update
        database-platform:  org.hibernate.dialect.MySQL8Dialect
    logging:
      level:
        root: error
    

    这个配置文件的作用和我们之前SSM项目的spring-jpa.xml文件的作用一样,不过更为简洁,注意,如果不配置database-platform: org.hibernate.dialect.MySQL8Dialect,那么默认创建的数据库表的引擎的MYISAM,如果配置了就是innoDB。然后配置了日志级别。其余的配置和SSM项目整合spring-data-jpa一样了。

    2、整合swagger

    Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

    总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。

    2.1 添加依赖

    这里只能自己创建项目后手动添加依赖,需要添加两个依赖:

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    

    2.2 添加配置

    swagger:
      basePackage: com.qianfeng
      title: User CRUD JPA SWAGGER
      version: v1.0
      description: this is a employee crud function
      contact: huwenlong
      url: www.baidu.com
    

    特别注意,swagger与日志不能同时使用,否则后台会一直停在一个地方,basePackage配置了将要扫描的包。

    2.3 创建配置类

    SwaggerConfigure.java

    package com.qianfeng.configure;
    
    import org.springframework.beans.factory.annotation.Value;
    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;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfigure {
        @Value("${swagger.title}")
        private String title;
        @Value("${swagger.basePackage}")
        private String basePackage;
        @Value("${swagger.version}")
        private String version;
        @Value("${swagger.description}")
        private String description;
        @Value("${swagger.contact}")
        private String contact;
        @Value("${swagger.url}")
        private String url;
        @Bean
        public Docket api(){
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.basePackage(basePackage))
                    .paths(PathSelectors.any())
                    .build();
        }
    
        private ApiInfo apiInfo(){
            return new ApiInfoBuilder()
                    .title(title)
                    .description(description)
                    .termsOfServiceUrl(url)
                    .version(version)
                    .contact(new Contact(contact,url,url))
                    .build();
        }
    }
    

    @Value注解从yml文件中读取配置信息并注入

    2.4 修改entity

    Employee.java

    package com.qianfeng.entity;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    
    import javax.persistence.*;
    
    @Entity
    @Table(name = "employee")
    @ApiModel(value = "员工对象",description = "对应员工表")
    public class Employee {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "emp_id",length = 10)
        @ApiModelProperty(name = "eid",example = "1")
        private int eid;
        @Column(name = "emp_name",unique = true,nullable = false,length = 20)
        @ApiModelProperty(name = "empName",example = "张三")
        private String empName;
        @Column(nullable = false,length = 30)
        @ApiModelProperty(name = "password",example = "zhansan123")
        private String password;
        @Column(nullable = false,length = 3)
        @ApiModelProperty(name = "age",example = "21")
        private int age;
        @Column(nullable = false)
        @ApiModelProperty(name = "address",example = "江苏省南京市")
        private String address;
    
        public Employee() {
        }
    
        public Employee(int eid, String empName, String password, int age, String address) {
            this.eid = eid;
            this.empName = empName;
            this.password = password;
            this.age = age;
            this.address = address;
        }
    
        public int getEid() {
            return eid;
        }
    
        public void setEid(int eid) {
            this.eid = eid;
        }
    
        public String getEmpName() {
            return empName;
        }
    
        public void setEmpName(String empName) {
            this.empName = empName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("Employee{");
            sb.append("eid=").append(eid);
            sb.append(", empName='").append(empName).append('\'');
            sb.append(", password='").append(password).append('\'');
            sb.append(", age=").append(age);
            sb.append(", address='").append(address).append('\'');
            sb.append('}');
            return sb.toString();
        }
    }
    

    增加了两个注解:@ApiModel与@ApiModelProperty,后者的name必须和作用的成员变量的名称相同

    2.5 修改controller

    EmployeeController.java

    package com.qianfeng.controller;
    
    import com.qianfeng.entity.Employee;
    import com.qianfeng.service.IEmployeeService;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.web.bind.annotation.*;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    @RestController
    public class EmployeeController {
        @Resource
        private IEmployeeService employeeService;
        @PostMapping("/saveEmployee")
        @ApiOperation("新增或更新员工信息")
        public Employee saveEmployee(Employee employee){
            return employeeService.saveEmployee(employee);
        }
        @GetMapping("/Emps")
        @ApiOperation("获取所有的员工信息")
        public List<Employee> getAllEmps(){
            return employeeService.getAllEmployees();
        }
        @GetMapping("/emp/{eid}")
        @ApiOperation("根据员工id获取特定员工的信息")
        public Employee getEmployeeById(@PathVariable int eid){
            return employeeService.getEmployeeById(eid);
        }
        @DeleteMapping("/emp/{eid}")
        @ApiOperation("根据员工id删除一个员工")
        public void deleteEmployeeById(@PathVariable int eid){
            employeeService.deleteEmployeeById(eid);
        }
    }
    

    每一个方法都添加了一个@ApiOperation注解,里面的值是对当前方法的解释。启动服务器后需要访问${你的地址与端口号}/swagger-ui.html

    相关文章

      网友评论

          本文标题:SpringBoot整合JPA与Swagger

          本文链接:https://www.haomeiwen.com/subject/zhijmhtx.html