SpringBoot+MyBatisPlus+Swagger2整合进行增删改查

前言:
本片文章采用的是SpringBoot+MybatisPlus+Swagger2,目的是使用
MybatisPlus完成增删改查操作。

  • 1、基本的增删改查
    MybatisPlus官网(官网内容很详细哦):https://mp.baomidou.com/

一、增删改查操作

1.Sql语句

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  `age` int(11) DEFAULT NULL COMMENT '年龄',
  `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

SET FOREIGN_KEY_CHECKS = 1;

2.项目结构

image.png

3.使用自动生成插件-生成代码

大家可以参考这篇文章EasyCode(代码神器)
既然是使用了MybatisPlus的话,我们可以将插件自动生成的代码进行删除。

  • UserDao.xml


    UserDao.xml
  • UserDao.java
    删除多余代码并使该接口继承BaseMapper
    image.png

顺便将service和controller生成的多余代码删除,要不然会报错!

4.pom.xml

 
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            com.baomidou
            mybatis-plus-boot-starter
            3.3.1.tmp
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        

        
            mysql
            mysql-connector-java
            runtime
        

        
            org.projectlombok
            lombok
            true
        


        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        

        
            io.springfox
            springfox-swagger2
            2.5.0
        
        
            com.github.xiaoymin
            swagger-bootstrap-ui
            1.9.3
        

5 配置文件

application.yml

spring:
#  数据源
  datasource:
#    用户名
    username: root
#    密码
    password: 123456
#    链接
    url: jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
#    驱动
    driver-class-name: com.mysql.jdbc.Driver
#mybatis-plus 配置
mybatis-plus:
  mapper-locations: classpath:/mapper/*Dao.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.mp.helo.entity

6 配置类

Swagger2Configuration.java

@Configuration
@EnableSwagger2
public class Swagger2Configuration {

    public static final String VERSION = "1.0.0";
    //api接口包扫描路径
    public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.mp.helo.controller";
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("MP接口测试") //设置文档的标题
                .description("MybatisPlus接口测试") // 设置文档的描述
                .version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
                .termsOfServiceUrl("[email protected]") // 设置文档的License信息->1.3 License information
                .build();
    }
}

6 entity

User.java

@Data
public class User implements Serializable {
    private static final long serialVersionUID = -23543490379469815L;
    /**
    * 主键ID
    */
    @TableId(value = "id",type = IdType.AUTO)
    private Long id;
    /**
    * 姓名
    */
    private String name;
    /**
    * 年龄
    */
    private Integer age;
    /**
    * 邮箱
    */
    private String email;

}

7 dao

UserDao.java

@Mapper
public interface UserDao extends BaseMapper {
}

8 service

UserService.java

/**
 * (User)表服务接口
 *
 * @author makejava
 * @since 2020-05-16 23:11:09
 */
public interface UserService extends IService{
}

UserServiceImpl.java

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2020-05-16 23:11:09
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl implements UserService {
}

9 controller

UserController.java

@Api(description = "用户API接口")
@RestController
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

   @ApiOperation(value = "新增")
    @PostMapping("insert")
    public boolean insert(@RequestBody User user){
        return this.userService.save(user);
    }

    @ApiOperation(value = "修改")
    @PostMapping("update")
    public boolean update(@RequestBody User user){
        return this.userService.updateById(user);
    }

    @ApiOperation(value = "删除")
    @GetMapping("deleteById")
    public boolean deleteById(@RequestParam("id") Integer id){
        return this.userService.removeById(id);
    }

    @ApiOperation(value = "批量删除")
    @GetMapping("deleteBatchById")
    public boolean deleteBatchById(@RequestBody List id){
        return this.userService.removeByIds(id);
    }

    @ApiOperation(value = "根据ID查询")
    @GetMapping("quertUserById")
    public User quertUserById(@RequestParam("id") Integer id){
        return this.userService.getById(id);
    }

    @ApiOperation(value = "分页查询")
    @GetMapping("quertUserByPage")
    public IPage quertUserByPage(@RequestParam("page") Integer page, @RequestParam("limit") Integer limit){
        Page userPage = new Page<>();
        IPage userIPage = this.userService.page(userPage);
        return userIPage;
    }


   
}

10 启动类

HeloApplication.java

@EnableSwagger2
@SpringBootApplication
@MapperScan("com.mp.helo.dao")
public class HeloApplication {
    public static void main(String[] args) {
        SpringApplication.run(HeloApplication.class, args);
    }
}

访问地址:http://127.0.0.1:8080/doc.html

11 测试

image.png

11.1 添加

image.png

可能出现的问题:

  "message": "nested exception is org.apache.ibatis.reflection.ReflectionException: Could not set property 'id' of 'class com.mp.helo.entity.User' with value '1236448483748507649' Cause: java.lang.IllegalArgumentException: java.lang.ClassCastException@3a92a1b",

解决办法:
在主键ID上加上该注解即可:
@TableId(type = IdType.AUTO,value = "id")

11.2删除

image.png

11.3 修改

image.png

11.4 分页查询

image.png

11.5 根据ID查询

image.png

代码链接:

链接:https://pan.baidu.com/s/1uEgdRn0twC7CyNd3ciXISQ 密码:62gq

你可能感兴趣的:(SpringBoot+MyBatisPlus+Swagger2整合进行增删改查)