Mybatis-Plus 官网:https://mp.baomidou.com/
注解使用:https://mp.baomidou.com/guide/annotation.htm
Github:https://github.com/baomidou/mybatis-plus

1、什么是MyBatis-Plus

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
mybatis plus 官网
建议安装 MybatisX 插件

只需要我们的Mapper继承 BaseMapper 就可以拥有crud能力

2、Quick start

mybatis-plus quick start:https://baomidou.com/guide/quick-start.html

文件目录结构

image.png

2.1、引入 MyBatis-Plus

  1. <dependency>
  2. <groupId>com.baomidou</groupId>
  3. <artifactId>mybatis-plus-boot-starter</artifactId>
  4. <version>3.4.2</version>
  5. </dependency>

image.png

2.2、配置 @MapperScan 注解

如果是放在主程序所在的包,@MapperScan 注解可以不写参数。

  1. package com.example.boot;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @MapperScan("com.example.boot")
  6. @SpringBootApplication
  7. public class SpringBootApiTest01Application {
  8. public static void main(String[] args) {
  9. SpringApplication.run(SpringBootApiTest01Application.class, args);
  10. }
  11. }

2.3、编写 Bean

Role

  1. package com.example.boot.bean;
  2. import com.baomidou.mybatisplus.annotation.TableName;
  3. import lombok.Data;
  4. @Data
  5. @TableName("t_s_role")
  6. public class Role {
  7. private String id;
  8. private String rolecode;
  9. private String rolename;
  10. private String role_type;
  11. }

2.4、编写 Mapper 接口

继承 BaseMapper
RoleMapper

  1. package com.example.boot.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.example.boot.bean.Role;
  4. public interface RoleMapper extends BaseMapper<Role> {
  5. }

2.5、编写 controller

/role 接口,当不传递 id 时

  1. package com.example.boot.controller;
  2. import com.example.boot.mapper.RoleMapper;
  3. import com.example.boot.response.Response;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.web.bind.annotation.GetMapping;
  7. import org.springframework.web.bind.annotation.RequestParam;
  8. import org.springframework.web.bind.annotation.RestController;
  9. @RestController
  10. @Slf4j
  11. public class RoleController extends BaseRestController {
  12. public RoleController() {
  13. log.info("RoleController 构造函数被调用了");
  14. }
  15. @Autowired
  16. private RoleMapper roleMapper;
  17. @GetMapping(path = {
  18. "/role",
  19. })
  20. public Response role(@RequestParam(name = "id", defaultValue = "") String id) {
  21. if (id == null || id.length() <= 0) {
  22. // 查全部 role
  23. return success("ok", roleMapper.selectList(null));
  24. } else {
  25. // 查单个 role
  26. return success("ok", roleMapper.selectById(id));
  27. }
  28. }
  29. }

2.7、测试

单个
http://127.0.0.1/role?id=8a8ab0b246dc81120146dc8181870050
image.png

多个
http://127.0.0.1/role
image.png