今天通过项目展示springboot+mybatis-plus+swagger2相结合,进行前后端分离,前后端联调 话不多说,先展示项目结构
步骤
书写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
书写配置类(创建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 {
@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;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("FIVEGROUP")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yaokui.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>());
}
}
书写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;
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;
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;
@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())){
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);
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;
@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;
@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
private long deleted;
@ApiModelProperty("班级编号")
private Integer cid;
@TableField(exist = false)
private Classes classes;
}
package com.yaokui.domain.vo;
import lombok.Data;
@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;
@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;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@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.*;
@RestController
@Api(value = "学生接口类")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;
@ApiOperation(value = "查询所有学生信息")
@PostMapping("getAll/{page}/{pageSize}")
public ReturnData getAll(
@RequestBody UserVo userVo
){
return userService.selectUserByPage(userVo);
}
@GetMapping("selectUserById/{id}")
@ApiOperation(value = "根据id查询学生信息")
public ReturnData selectUserById(@PathVariable Integer id){
return userService.selectOne(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中展示一下页面
可以看的出来我们在controller的写得所有的请求都被展示在这里
查询
删除
添加
根据id进行查询
修改