1.springboot整合swagger2
1.1 什么是swagger2
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务。
及时性(接口变更后,能够及时准确的通知前后端开发人员)
规范性(并且保证接口的规范性,如接口的地址,请求方式,参数,响应格式和错误信息)
一致性(接口信息一致,不糊出现文档版本不一致产生分歧)
可测性(直接在接口文档上进行测试)
1.2 为什么要用swagger2
目前的项目基本都是[前后端分离],后端为前端提供接口的同时,还需同时提供接口的说明文档。但我们的代码
总是会根据实际情况来实时更新,这个时候有可能会忘记更新接口的说明文档,造成一些不必要的问题。
1.3 如何使用接口文档swagger2
(1) 引入依赖
<!--swagger2依赖-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.1.RELEASE</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.7.8</version>
</dependency>
(2) 创建一个配置类-swagger2
@Configuration
@EnableSwagger2 //开启seagger注解驱动
public class SwaggerConfig {
@Bean
public Docket docket(){
Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("QY163")
.apiInfo(getInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.hm.controller"))
.build();
return docket;
}
private ApiInfo getInfo(){
Contact DEFAULT_CONTACT = new Contact("胡萌", "http://www.baidu.com", "1804965659@qq.com");
ApiInfo apiInfo=new ApiInfo("QY163心里测试系统API", "QY163心里测试系统API", "1.1.0", "http://www.jd.com",
DEFAULT_CONTACT, "志远科技", "http://www.aaa.com", new ArrayList<VendorExtension>());
return apiInfo;
}
}
(3) 访问swagger在线文档 有两个路径
第一个路径
http://ip:port/swagger-ui.html路径
第二个路径
1.4 swagger中常用的注解
@Api(tags="")----使用在controller类上
@ApiOperation(value="")-----接口方法上 接口方法加以说明
@ApiParam(value = "",name = "",required = true)
@ApiModel----实体类
@ApiModelProperty----->实体类的属性说明
2.springboot整合mybatis-plus整合swagger2完成增删改查(基于学生表和班级表)
2.1 先创建一个springboot工程
1. 在 application.properties配置文件中添加 MYSQL 数据库的相关配置:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql:///work
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
2. 引入 Spring Boot Starter 父工程:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5+ 版本</version>
<relativePath/>
</parent>
引入相关依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
//注意:这里引入mybatis-plus依赖,就可以不用引入mybatis依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>最新版本</version>
</dependency>
3 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 mapper文件夹:
swagger2配置文件
@Configuration
@EnableSwagger2 //开启seagger注解驱动
public class SwaggerConfig {
@Bean
public Docket docket(){
Docket docket = new Docket(DocumentationType.SWAGGER_2).groupName("QY163")
.apiInfo(getInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.hm.controller"))
.build();
return docket;
}
private ApiInfo getInfo(){
Contact DEFAULT_CONTACT = new Contact("hm", "http://www.baidu.com", "1804965659@qq.com");
ApiInfo apiInfo=new ApiInfo("QY163心里测试系统API", "QY163心里测试系统API", "1.1.0", "http://www.jd.com",
DEFAULT_CONTACT, "志远科技", "http://www.aaa.com", new ArrayList<VendorExtension>());
return apiInfo;
}
}
学生实体类和班级实体类
@Data
@ApiModel(value = "学生实体类")//使用swagger2Api来标注
public class Student implements Serializable {
/**
*//由于mybatis-plus中主键默认是id,这里是sid,所以加上@TableId(type = IdType.AUTO)注解并且递增
*/
@TableId(type = IdType.AUTO)
@ApiModelProperty(value = "学生编号")
private Integer sid;
/**
*
*/
@ApiModelProperty(value = "学生姓名")
private String sname;
/**
*
*/
@ApiModelProperty(value = "学生年龄")
private Integer age;
/**
*
*/
@ApiModelProperty(value = "班级编号")
private Integer cid;
@TableField(exist = false)//多表联查,引入班级实体类
private Class aaa;
public Student() {
}
public Student(Integer sid, String sname, Integer age, Integer cid) {
this.sid = sid;
this.sname = sname;
this.age = age;
this.cid = cid;
}
public Student(String sname, Integer age, Integer cid) {
this.sname = sname;
this.age = age;
this.cid = cid;
}
private static final long serialVersionUID = 1L;
}
@Data
@ApiModel(value = "班级实体类")
public class Class implements Serializable {
/**
*
*/
//由于mybatis-plus中主键默认是id,这里是cid,所以加上@TableId(type = IdType.AUTO)注解并且递增
@TableId(type = IdType.AUTO)
@ApiModelProperty(value = "班级编号")
private Integer cid;
/**
*
*/
@ApiModelProperty(value = "班级名称")
private String cname;
private static final long serialVersionUID = 1L;
}
定义一个StudentVo类 用来作为条件
@ApiModel(value = "接收学生的请求参数")
public class StudentVo {
@ApiModelProperty(value = "学生编号")
private String sid;
@ApiModelProperty(value = "学生的名称")
private String sname;
@ApiModelProperty(value = "学生的年龄")
private String age;
private String cid;
public String getSid() {
return sid;
}
public void setSid(String sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public StudentVo(String sid, String sname, String age, String cid) {
this.sid = sid;
this.sname = sname;
this.age = age;
this.cid = cid;
}
}
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hm.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.hm.pojo.entity.Student" autoMapping="true">
<id property="sid" column="sid" jdbcType="INTEGER"/>
//这里是多表关联,需要association 来关联
<association property="aaa" javaType="com.hm.pojo.entity.Class" autoMapping="true">
<id property="cid" column="cid"/>
</association>
</resultMap>
<select id="findByPage" resultMap="BaseResultMap">
select * from student t join class c on t.cid=c.cid
<if test="ew!=null and ew.sqlSegment!=''">
<where> and ${ew.sqlSegment} </where>
</if>
</select>
</mapper>
Mapper层
public interface StudentMapper extends BaseMapper<Student> {
IPage<Student> findByPage(IPage<Student> iPage,@Param("ew") Wrapper<Student> wrapper);
}
service层
public interface StudentService{
//vo:view Object 接受前端请求的数据对象
Result findByPage(Integer current, Integer pageSize, StudentVo studentVo);
Result updateById(Student student);
Result deleteById(Integer sid);
Result deleteBatchIds(List<Integer> ids);
Result insert(Student student);
}
ServiceImpl
@Service
public class StudentServiceImpl implements StudentService{
@Resource
private StudentMapper studentMapper;
@Override
public Result findByPage(Integer current, Integer pageSize, StudentVo studentVo) {
//分页对象
Page<Student> page=new Page<>(current,pageSize);
//条件对象-- xml
QueryWrapper<Student> wrapper=new QueryWrapper<>();
//判断是否为空
if (StringUtils.hasText(studentVo.getSid())){
wrapper.eq("sid",studentVo.getSid());
}
if (StringUtils.hasText(studentVo.getSname())){
wrapper.like("sname",studentVo.getSname());
}
if (StringUtils.hasText(studentVo.getAge())){
wrapper.ge("age",studentVo.getAge());
}
IPage<Student> byPage = studentMapper.findByPage(page, wrapper);
return new Result(200,"分页查询学生成功",byPage);
}
@Override
public Result updateById(Student student) {
return new Result(200,"修改学生成功",studentMapper.updateById(student));
}
@Override
public Result deleteById(Integer sid) {
return new Result(200,"删除成功",studentMapper.deleteById(sid));
}
@Override
public Result deleteBatchIds(List<Integer> ids) {
int i = studentMapper.deleteBatchIds(ids);
if (i>0){
return new Result(200,"删除成功",i);
}else{
return new Result(500,"删除失败",i);
}
}
@Override
public Result insert(Student student) {
int insert = studentMapper.insert(student);
if (insert>0){
return new Result(200,"添加成功",insert);
}else{
return new Result(500,"添加失败",insert);
}
}
}
Contrller层
@RestController
@RequestMapping("student")
@Api(tags = "学生操作API")
public class StudentController {
@Autowired
private StudentService studentService;
@Resource
private StudentMapper studentMapper;
@PostMapping("list/{current}/{pageSize}")
@ApiOperation(value = "根据条件分页查询学生信息")
public Result list(
@ApiParam(value = "当前页面", name = "current", required = true, defaultValue = "1")
@PathVariable Integer current,
@ApiParam(value = "当前页数", name = "pageSize", required = true, defaultValue = "5")
@PathVariable Integer pageSize,
@RequestBody StudentVo studentVo) {
return studentService.findByPage(current, pageSize, studentVo);
}
//@PutMapping 查询 get提交 删除 delete 修改 PUT提交 添加 post提交
/*查 根据id查询*/
@GetMapping("findById/{sid}")
@ApiOperation(value = "根据id查询学生信息")
public Student findAById(
@ApiParam(value = "学生id", name = "sid", required = true)
@PathVariable Integer sid
){
Student student = studentMapper.selectById(sid);
return student;
}
/*增*/
@PostMapping("insert")
@ApiOperation(value = "新增学生信息")
public Result insert(@RequestBody Student student){
return studentService.insert(student);
}
/*改*/
@PutMapping("update")
@ApiOperation(value = "根据id修改学生信息")
public Result update(@RequestBody Student student){
System.out.println(student);
return studentService.updateById(student);
}
/*删*/
@DeleteMapping("delete/{sid}")
@ApiOperation(value = "根据删除学生信息")
public Result delete(
@ApiParam(value = "学生id", name = "sid", required = true)
@PathVariable Integer sid
){
Result result = studentService.deleteById(sid);
return result;
}
/*批量删除*/
@PostMapping("deleteList")
public Result deleteList(@RequestBody List<Integer> ids){
System.out.println(ids);
return studentService.deleteBatchIds(ids);
}
}
测试 路径:http://localhost:8080/doc.html