Springboot 整合 JPA 及 Swagger2
首先是官方文档:
Spring Data JPA - Reference Documentation
https://docs.spring.io/spring-data/jpa/docs/2.2.4.RELEASE/reference/html/#repositories.query-methods
1、JPA相关概念
2、创建 Springboot 项目
修改 pom 文件,可以直接进行复制粘贴,web依赖及JPA依赖。
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.11</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>mybatisdemo</artifactId><version>0.0.1-SNAPSHOT</version><name>mybatisdemo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>
yml配置文件如下:要注意驱动的版本及数据库名称。
spring:jpa:show-sql: truehibernate:ddl-auto: updatedatasource:url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMTusername: rootpassword: 1111driver-class-name: com.mysql.cj.jdbc.Driver
创建一个实体类:案例结构如下,可以按照这个来进行创建,实体类,service,dao,controller
创建一个dao包,要继承于
JpaRepository,
第一个是实体类,第二个是实体类主键的类型。
package com.example.mybatisdemo.dao;import com.example.mybatisdemo.model.Account;
import org.springframework.data.jpa.repository.JpaRepository;public interface AccountDao extends JpaRepository<Account,Integer> {
}
如下是JPA自带的一些方法,可以进行源码查看,如下;
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//package org.springframework.data.jpa.repository;import java.util.List;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;@NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {List<T> findAll();List<T> findAll(Sort sort);List<T> findAllById(Iterable<ID> ids);<S extends T> List<S> saveAll(Iterable<S> entities);void flush();<S extends T> S saveAndFlush(S entity);<S extends T> List<S> saveAllAndFlush(Iterable<S> entities);/** @deprecated */@Deprecateddefault void deleteInBatch(Iterable<T> entities) {this.deleteAllInBatch(entities);}void deleteAllInBatch(Iterable<T> entities);void deleteAllByIdInBatch(Iterable<ID> ids);void deleteAllInBatch();/** @deprecated */@DeprecatedT getOne(ID id);/** @deprecated */@DeprecatedT getById(ID id);T getReferenceById(ID id);<S extends T> List<S> findAll(Example<S> example);<S extends T> List<S> findAll(Example<S> example, Sort sort);
}
创建一个Service包。
package com.example.mybatisdemo.service;import com.example.mybatisdemo.model.Account;import java.util.List;public interface AccountService {List<Account> findAll();
}
创建一个实现类impl
package com.example.mybatisdemo.service.impl;import com.example.mybatisdemo.dao.AccountDao;import com.example.mybatisdemo.model.Account;
import com.example.mybatisdemo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class AccountServiceImpl implements AccountService {@Autowiredprivate AccountDao accountDao;@Overridepublic List<Account> findAll() {return accountDao.findAll();}
}
实体类:
package com.example.mybatisdemo.model;import lombok.*;
import javax.persistence.Id;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import java.io.Serializable;@Entity
@Table(name="account")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Account implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;private String name;private double money;
}
controller:
package com.example.mybatisdemo.controller;import com.example.mybatisdemo.model.Account;
import com.example.mybatisdemo.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
@RequestMapping("/account")
public class AccountController {@Autowiredprivate AccountService accountService;@RequestMapping("/findAll")public List<Account> findAll(){return accountService.findAll();}
}
以上是整合JPA部分,接下来套上 Swagger2。
3、整合Swagger2
(1)Swagger简介:
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
(2)Swagger 的API说明:
(3)具体使用:
添加 pom 依赖。
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version><exclusions><exclusion><groupId>io.swagger</groupId><artifactId>swagger-models</artifactId></exclusion></exclusions>
</dependency>
<dependency><groupId>io.swagger</groupId><artifactId>swagger-models</artifactId><version>1.5.22</version>
</dependency>
修改yml配置文件,下面Mvc相关配置必须加上,不然会报错。因为版本问题。
spring:jpa:show-sql: truehibernate:ddl-auto: updatedatasource:url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMTusername: rootpassword: 1111driver-class-name: com.mysql.cj.jdbc.Drivermvc:pathmatch:matching-strategy: ant_path_matcher
management:endpoints:web:exposure:include: health
新建一个config文件夹。如下图所示创建即可。
代码如下:注意代码中的路径。
package com.example.mybatisdemo.config;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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class AppSwaggerConfig {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.example.mybatisdemo")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("曹俊测试Swagger接口文档").description("测试模块").version("1.0.release").build();}
}
修改实体类如下:添加上相关字段描述即可。
package com.example.mybatisdemo.model;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import javax.persistence.Id;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Table;
import java.io.Serializable;@Entity
@Table(name="account")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
@ApiModel(description = "用户账户表")
public class Account implements Serializable {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@ApiModelProperty(value = "ID")private Integer id;@ApiModelProperty(value = "姓名")private String name;@ApiModelProperty(value = "账户余额")private double money;
}
创建一个dto文件夹,里面添加两个文件 Result PageResult
代码如下:
package com.example.mybatisdemo.dto;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "数据传输对象-通用结果")
public class Result {@ApiModelProperty(value = "操作结果")private boolean success;@ApiModelProperty(value = "操作消息")private String message;}
package com.example.mybatisdemo.dto;import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.List;@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(description = "数据传输对象-分页结果")
public class PageResult {@ApiModelProperty(value = "总条数")Long total;@ApiModelProperty(value = "结果集")List rows;
}
在controller上面进行修改。添加相关的CRUD代码:
package com.example.mybatisdemo.controller;import com.example.mybatisdemo.dao.AccountDao;
import com.example.mybatisdemo.dto.PageResult;
import com.example.mybatisdemo.dto.Result;
import com.example.mybatisdemo.model.Account;
import com.example.mybatisdemo.service.AccountService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/account")
@Api(tags = "用户管理")
public class AccountController {@Autowiredprivate AccountService accountService;@Autowiredprivate AccountDao accountDao;@GetMapping("/findAll")@ApiOperation(value = "查询所有用户信息")public List<Account> findAll(){return accountService.findAll();}@PostMapping("/newAccount")@ApiOperation(value = "新增")public Result newAccount(Account account){try {accountService.newAccount(account);return new Result(true,"添加成功");}catch (Exception e){e.printStackTrace();return new Result(false,"添加失败");}}@GetMapping("/findPage/{currentPage}/{size}")@ApiOperation(value = "分页查询")@ApiImplicitParams({@ApiImplicitParam(name = "currentPage", value = "当前页码", required = true, dataTypeClass = Integer.class),@ApiImplicitParam(name = "size", value = "每页条数", required = true, dataTypeClass = Integer.class)})public PageResult findPage(@PathVariable("currentPage") int currentPage, @PathVariable("size") int size) {Page<Account> page = accountDao.findAll(PageRequest.of(currentPage, size));return new PageResult(page.getTotalElements(), page.getContent());}@GetMapping("/findPage2")@ApiOperation(value = "分页查询2")@ApiImplicitParams({@ApiImplicitParam(name = "currentPage", value = "当前页码", required = true, dataTypeClass = Integer.class),@ApiImplicitParam(name = "size", value = "每页条数", required = true, dataTypeClass = Integer.class)})public PageResult findPage2(@RequestParam("currentPage") int currentPage, @RequestParam("size") int size) {Page<Account> page = accountDao.findAll(PageRequest.of(currentPage, size));return new PageResult(page.getTotalElements(), page.getContent());}@GetMapping("/findOne")@ApiOperation(value = "根据id查询")@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "ID", required = true, dataTypeClass = Long.class)})public Account findOne(Integer id) {return accountDao.findById(id).get();}@GetMapping("/delete")@ApiOperation(value = "删除")@ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "ID集合", required = true, dataTypeClass = Long.class)})public Result delete(Integer[] ids) {try {for (Integer id : ids) {accountDao.deleteById(id);}return new Result(true, "删除成功");} catch (Exception e) {e.printStackTrace();return new Result(false, "删除失败");}}
}
最后启动项目进行测试
http://localhost:8080/swagger-ui.html