springboot+mybatis-plus+swagger2

今天通过项目展示springboot+mybatis-plus+swagger2相结合,进行前后端分离,前后端联调 话不多说,先展示项目结构

springboot+mybatis-plus+swagger2_第1张图片

步骤

书写springboot的配合文件

#配置数据源
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/mabitsplus?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.druid.username=root
spring.datasource.druid.password=root

#指定映射文件所在的路径
# mybatis-plus.config-location=classpath:mapper/*.xml

#mybatis日志文件
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

书写配置类(创建config包并新建两个类MybatisPlusConfig和SwaggerConfig)

package com.yaokui.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

}
package com.yaokui.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

/**
 *
 * @Return
 * @Author: 19649
 * @Date: 2023/4/12 19:08
 */

@Configuration
@EnableSwagger2
//@EnableWebMvc
public class SwaggerConfig {
   @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("FIVEGROUP")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yaokui.controller"))  //只为com.yaokui.controller包下的controller生生接口文档
                .build();
    }

    private ApiInfo apiInfo(){
        Contact DEFAULT_CONTACT = new Contact("FIVEGROUP"
                , "https://gitee.com/seventeens/springbootswagger.git"
                , "[email protected]");

        return new ApiInfo("FIVEGROUP学生系统系统API"
                , "FIVEGROUP学生系统系统API"
                , "3.1.1"
                , "https://www.nowcoder.com/exam/intelligent?questionJobId=10&tagId=21000",
                DEFAULT_CONTACT
                , "AAA网络科技有限公司"
                , "https://blog.csdn.net/weixin_52962125/article/details/130097963"
                , new ArrayList<VendorExtension>());
    }

   /* private ApiInfo apiInfo() {
        //Contact DEFAULT_CONTACT = new Contact("five","www.google.com","[email protected]");
        return new ApiInfoBuilder()
                .title("swagger和springBoot整合")
                .description("swagger的API文档")
                .version("2.0")
                .termsOfServiceUrl("www.baidu.com")
                .build();
    }*/

}

书写mapper层(需要继承BaseMapper类)

package com.yaokui.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yaokui.domain.entry.User;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.apache.ibatis.annotations.Param;

/**
 *@ClassName UserMapper
 *@Description TODO
 *@Author 19649
 *@Date 2023/4/12 19:24
 */
public interface UserMapper extends BaseMapper<User> {
    IPage<User> selectUserByPage(IPage<User> iPage,@Param("ew") Wrapper<User> wrapper);
}

书写service层(包括service类和实现类)

package com.yaokui.service;

import com.yaokui.domain.vo.PageEntity;
import com.yaokui.domain.vo.UserVo;
import com.yaokui.utils.ReturnData;

/**
 * 功能描述
 *
 * @author 19649
 * @date 2023/04/12  18:13
 */
public interface UserService {

    ReturnData selectUserByPage(UserVo userVo);

    ReturnData selectOne(Integer id);
}

package com.yaokui.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Converter;
import com.yaokui.domain.entry.User;
import com.yaokui.domain.vo.UserVo;
import com.yaokui.mapper.UserMapper;
import com.yaokui.service.UserService;
import com.yaokui.utils.ReturnData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 *@ClassName UserServiceImpl
 *@Description
 *@Author 19649
 *@Date 2023/4/12 18:09
 */

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ReturnData selectOne(Integer id) {
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, id));
        return new ReturnData(200,"success",user);
    }

    //多表分页查询
    @Override
    public ReturnData selectUserByPage(UserVo userVo) {

        IPage<User> iPage=new Page<>(userVo.getPageIndex(),userVo.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = new QueryWrapper<User>().lambda();
        //判断用户名是否为空
        if(StringUtils.hasText(userVo.getUsername())){
            //wrapper.like("username",userVo.getUsername());
            queryWrapper.like(User::getUsername,userVo.getUsername());
        }
        //判断用户名是否为空
        if(StringUtils.hasText(userVo.getName())){
            queryWrapper.like(User::getName,userVo.getName());
        }
        //判断用户名是否为空
        if(userVo.getAge()!=null){
            queryWrapper.eq(User::getAge,userVo.getAge());
        }
        //判断用户名是否为空
        if(StringUtils.hasText(userVo.getEmail())){
            queryWrapper.like(User::getEmail,userVo.getEmail());
        }
        this.userMapper.selectUserByPage(iPage,queryWrapper);
        //this.userMapper.selectPage(iPage,wrapper);
        return new ReturnData(200,"分页查询成功",iPage);
    }



}

domain中创建两种实体,一种是后端(entry),一种是前端参数(vo)

package com.yaokui.domain.entry;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 *
 * @Return
 * @Author: 19649
 * @Date: 2023/4/12 19:08
 */

@ApiModel("班级实体")
public class Classes {

  @ApiModelProperty("班级号")
  @TableId(type = IdType.AUTO)
  private long cid;
  @ApiModelProperty("班级名称")
  private String cname;
  @ApiModelProperty("容纳人数")
  private long capacity;


  public long getCid() {
    return cid;
  }

  public void setCid(long cid) {
    this.cid = cid;
  }


  public String getCname() {
    return cname;
  }

  public void setCname(String cname) {
    this.cname = cname;
  }


  public long getCapacity() {
    return capacity;
  }

  public void setCapacity(long capacity) {
    this.capacity = capacity;
  }

}

package com.yaokui.domain.entry;

import com.baomidou.mybatisplus.annotation.*;
import com.yaokui.domain.vo.PageEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
/**
 *
 * @Return
 * @Author: yaokui
 * @Date: 2023/4/12 19:29
 */
@ToString
@Data
@ApiModel("学生实体")
public class User extends PageEntity {

  @ApiModelProperty("学生编号")
  @TableId(type = IdType.AUTO)
  private Integer id;
  @ApiModelProperty("用户名")
  private String username;

  @TableField(select = false,fill = FieldFill.INSERT)//插入数据时进行填充
  private String password;
  @ApiModelProperty("姓名")
  private String name;

  @ApiModelProperty("年龄")
  private Integer age;
  @ApiModelProperty("邮箱")
  private String email;

  @ApiModelProperty("修改版本号")
  @Version
  private String version;

  @ApiModelProperty("逻辑删除")
  @TableLogic//逻辑删除 0表示未删除  1表示已删除
  private long deleted;

  @ApiModelProperty("班级编号")
  private Integer cid;

  @TableField(exist = false)
  private Classes classes;


}

package com.yaokui.domain.vo;/**
 * 功能描述
 *
 * @author 19649
 * @date 2023/04/12  22:20
 */

import lombok.Data;

/**
 *@ClassName PageEntity
 *@Description TODO
 *@Author 19649
 *@Date 2023/4/12 22:20
 */
@Data
public class PageEntity {
    private int pageSize;
    private int pageIndex;

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        if(pageSize==0){
            this.pageSize = 10;
            return;
        }
        this.pageSize = pageSize;
    }

    public int getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }
}

package com.yaokui.domain.vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 *@ClassName UserVo
 *@Description  前端参数接口
 *@Author 19649
 *@Date 2023/4/12 18:26
 */
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor

@ApiModel(value = "接受学生的请求参数")
public class UserVo extends PageEntity  {

    @ApiModelProperty("用户名")
    private String username;

    @ApiModelProperty("姓名")
    private String name;
    @ApiModelProperty("年龄")
    private Integer age;
    @ApiModelProperty("邮箱")
    private String email;

}

创建utils包工具类

package com.yaokui.utils;/**
 * 功能描述
 *
 * @author 19649
 * @date 2023/04/12  18:25
 */

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

/**
 *@ClassName ReturnData
 *@Description json
 *@Author 19649
 *@Date 2023/4/12 18:25
 */

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class ReturnData {
    private Integer code;
    private String msg;
    private Object data;
}

Controller层

package com.yaokui.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yaokui.domain.entry.User;
import com.yaokui.domain.vo.UserVo;
import com.yaokui.mapper.UserMapper;
import com.yaokui.service.UserService;
import com.yaokui.utils.ReturnData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 *@ClassName UserController
 *@Description TODO
 *@Author 19649
 *@Date 2023/4/12 18:15
 */
@RestController
@Api(value = "学生接口类")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;
    //分页查询

    @ApiOperation(value = "查询所有学生信息")
    @PostMapping("getAll/{page}/{pageSize}")
    public ReturnData getAll(
          //@ApiParam(name ="page" ,value = "当前页面",required = true,defaultValue = "1")
         // @PathVariable  Integer page,
          //@ApiParam(name ="pageSize" ,value = "每页条数",required = true,defaultValue = "6")
         // @PathVariable Integer pageSize,
          @RequestBody UserVo userVo
            ){
        return userService.selectUserByPage(userVo);
    }
    //根据id进行查询
    @GetMapping("selectUserById/{id}")
    @ApiOperation(value = "根据id查询学生信息")
    public ReturnData selectUserById(@PathVariable Integer id){

        return userService.selectOne(id);
        //return new ReturnData(200,"根据id查询成功",this.userMapper.selectById(id));
    }
    //新增学生信息
    @PostMapping("insertUser")
    @ApiOperation(value = "新增学生信息")
    public ReturnData insertUser(@RequestBody User user){
        User user1=new User();
        user1.setUsername(user.getUsername());
        user1.setName(user.getName());
        user1.setAge(user.getAge());
        user1.setEmail(user.getEmail());
        user1.setPassword(user.getPassword());
        return new ReturnData(200,"新增成功",this.userMapper.insert(user1));
    }
    //修改学生信息
    @PostMapping("/updateUser")
    @ApiOperation(value = "修改学生信息")
    public ReturnData updateUser(@RequestBody User user){
        User user1=new User();
        user1.setUsername(user.getUsername());
        user1.setName(user.getName());
        user1.setAge(user.getAge());
        user1.setEmail(user.getEmail());
        user1.setPassword(user.getPassword());
        UpdateWrapper<User> query =new UpdateWrapper<>();
        query.eq("id",user.getId());
        return new ReturnData(200,"修改成功",this.userMapper.update(user1,query));
    }
    //删除学生信息
    @DeleteMapping("deleteUser/{id}")
    @ApiOperation(value = "删除学生信息")
    public ReturnData deleteUser(@PathVariable Integer id){

        return new ReturnData(200,"删除成功",this.userMapper.deleteById(id));
    }
}

resources下创建mapperxml文件

<?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.yaokui.mapper.UserMapper">

    <resultMap id="findByPageResultMap" type="com.yaokui.domain.entry.User" autoMapping="true">
        <id column="id" property="id"/>
        <association property="classes" javaType="com.yaokui.domain.entry.Classes" autoMapping="true">
            <id property="cid" column="cid"/>
        </association>
    </resultMap>

    <!--<sql id="selectUC">
        username,password,name,age,email
        u.cid,cname, capacity
    </sql>-->
 <select id="selectUserByPage" resultMap="findByPageResultMap">
     select u.id,u.username, u.password, u.name, u.age, u.email,  u.cid,c.cname,
     c.capacity from user u join classes c on u.cid = c.cid and u.deleted=0
     <if test="ew!=null and ew.sqlSegment!=''">
         <where>
             and ${ew.sqlSegment}
         </where>
     </if>
    </select>

</mapper>

pom依赖

<?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.3.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yaokui</groupId>
    <artifactId>springbootswagger</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootswagger</name>
    <description>springbootswagger</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>
        </dependency>
        <!--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>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.12</version>
        </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>

http://localhost:8080/doc.html进入swagger2中展示一下页面springboot+mybatis-plus+swagger2_第2张图片

可以看的出来我们在controller的写得所有的请求都被展示在这里

springboot+mybatis-plus+swagger2_第3张图片

查询

springboot+mybatis-plus+swagger2_第4张图片

删除

springboot+mybatis-plus+swagger2_第5张图片

添加

springboot+mybatis-plus+swagger2_第6张图片

根据id进行查询

springboot+mybatis-plus+swagger2_第7张图片

修改

springboot+mybatis-plus+swagger2_第8张图片

你可能感兴趣的:(mybatis,spring,boot,java)