目的:使用springboot+jpa+swagger-ui实现简单的增删查改
注意事项:
这个启动项(SxgfTestApplication)一定要放在example下面,要不然swagger-ui无法扫描到这些接口,会出现报错。
Entity实体类:
package com.example.entity;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
@Table(name="sxgf_gf")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String sex;
private Integer age;
private String class1;
private String tel;
}
Get和set方法使用@Date注解帮我们生成,所以就不用写
Dao层:
package com.example.dao;
import com.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
//泛型中第一个参数是实体类,第二个是id类型
public interface UserDao extends JpaRepository<User,Integer> {
}
这里直接继承JpaRepository接口,后面直接对这个接口进行增删改查
Service层:
package com.example.service;
import com.example.dao.UserDao;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserSerice {
@Autowired
private UserDao userDao;
//插入一个用户
public User addUser(User user){
return userDao.save(user);
}
//修改一个用户
public User updateUser(User user){
return userDao.save(user);
}
//根据id删除一条数据
public void deleteUserById(Integer id){
userDao.deleteById(id);
}
//查询所有
public List<User> findAll(){
return userDao.findAll();
}
//根据id查询一条数据
public User findUserById(Integer id){
return userDao.findById(id).get();
}
}
Controller层:
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserSerice;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
@RequestMapping("/")
public class UserController {
@Autowired
private UserSerice userSerice;
//添加一个用户
@ApiOperation(value="添加一个用户", notes="输入信息即可添加成功")
@PostMapping( "/addUser")
@ResponseBody
public User addUser(String name, String sea,Integer age,String class1,String tel) {
User user1=new User();
user1.setName(name);
user1.setSex(sea);
user1.setAge(age);
user1.setClass1(class1);
user1.setTel(tel);
return userSerice.addUser(user1);
}
//根据id删除一条数据
@ApiOperation(value="根据id删除一条数据", notes="")
@DeleteMapping("/deleteUser/{id}")
public void deleteUserById(@PathVariable(name = "id", required = true) Integer id) {
userSerice.deleteUserById(id);
}
@ApiOperation(value="根据id查询一条数据", notes="")
@GetMapping("/findUserById/{id}")
@ResponseBody
public User findUserById(@PathVariable(name = "id") Integer id) {
return userSerice.findUserById(id);
}
@ApiOperation(value="查看所有的用户", notes="")
@GetMapping("/findAll")
@ResponseBody
public List<User> findAll() {
return userSerice.findAll();
}
//修改一个用户
@ApiOperation(value="修改一个用户", notes="可先查看所有用户的信息,然后在根据id进行修改")
@PutMapping("/updateUser")
@ResponseBody
public User updateUserById(Integer id, String name, String sea,Integer age,String class1,String tel) {
User user1=new User();
user1.setId(id);
user1.setName(name);
user1.setSex(sea);
user1.setAge(age);
user1.setClass1(class1);
user1.setTel(tel);
return userSerice.updateUser(user1);
}
}
Config层:
通过Swagger2Config这个类来扫描controller层下的接口
package com.example.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 Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.pathMapping("/")
.select()
.paths(PathSelectors.any())
//为当前包下controller生成API文档
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
//为有@Api注解的Controller生成API文档
// .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
//为有@ApiOperation注解的方法生成API文档
// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SwaggerUI演示")
.description("")
.contact("fbm")
.version("1.0")
.build();
}
}
配置文件:
spring:
mvc:
static-path-pattern:/static/**
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot?useSSL=false&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&serverTimezone=Asia/Shanghai
username: root
password: 12255899
initialSize: 20
minIdle: 50
maxActive: 500
application:
name: sxbs-mall-consumer
# 多个接口上的@FeignClient(“相同服务名”)会报错,overriding is disabled。
# 设置 为true ,即 允许 同名
main:
allow-bean-definition-overriding: true
jpa:
hibernate:
ddl-auto: update //如果数据库里面有表,可使用create语句来创建表
show-sql: true
pom.xml maven项目包,我全都粘贴在下边,如果有需要的可自行复制
<?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.1.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>sxgf_test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sxgf_test</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-web</artifactId>
</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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
最后我们运行一下项目:
如果说swager可以显示到上面那些接口,则说明成功了,如果没有可以看看我刚开始写的注意事项,或者路径问题,检查一下自己写的路径。