springboot整合mybatis-plus实现CRUD

本文详细介绍SpringBoot框架,从概念到优势,再到具体项目搭建过程,包括环境配置、依赖导入、项目结构、启动类、配置文件等内容。通过实例演示CRUD操作,涵盖添加、更新、查询和删除功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是springboot

 SprungBoot是一个快速整合第三方框架,简化xml配置完全采用注解化,内置Http服务器(如:Jetty和Tomcat),最终是以java应用程序进行执行。之前Web项目,变成War包放入Tomcat WebApps进行解压运行。

2.为什么要使用SpringBoot框架

咱们来看看下面这张图,

这是一个传统SSM项目的整合,分整合数据库访问层,业务逻辑层,事务配置,SpringMVC等等写很多配置文件,看上去特别麻烦和繁琐,整合的时候还特别容易出错,想想都折磨人。

比如之前整合传统主流SSH或者SSM,整合起来最大缺点:开发效率低,jar冲突(这是最恶心的),配置多,配置一多,就很容易报错。

现在这些问题统统解决了,我只需要引入一个依赖,迅速就把环境搭建起来了,这个框架就是SpringBoot,他的底层帮你实现版本统一,采用MAVEN继承原理实现的。

3.搭建一个SpringBoot项目

环境要求

Java1.8及以上

本文采用Java 1.8.0_73 . Spring Boot 2.0版本

导入项目maven依赖

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <!-- redis 集成-->
    <dependencies>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.13 </version>
        </dependency>


        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.5.1</version>
        </dependency>


        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.7</version>
        </dependency>



        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>

        <!-- sagger依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <!--mybatis起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>


        <!--mysql连接依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.46</version>
        </dependency>

        <!--web起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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


        <!--springboot起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>
    </dependencies>

    <build>
      <!--  <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>-->
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

项目结构:

启动类:

@SpringBootApplication
@MapperScan("com.zigao.com.mapper")
public class ZiGaoApplication {
    public static void main(String[] args) {
            SpringApplication.run(ZiGaoApplication.class, args);

        }
    }

项目配置文件

application.yml配置文件

server:
  port: 9999
spring:
  application:
    #项目名称
    name: zigao
  profiles:
    #环境
    active: dev

application-dev.yml配置文件

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mp?characterEncoding=utf-8&serverTimeZone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

common包下内容:

public enum CommonResponseCode implements IErrorMessage{


    Success("200", "操作成功", 0),
    NotFound("404", "请求不存在", 0),
    ServerError("500", "服务器错误", 0),

    IllegalArgument("1001", "参数错误:%s", 1),
    NoPermission("1002", "无权限", 0),
    NeedRefreshToken("1003", "需要刷新Token的TTL", 0),
    NotLogin("1004", "用户未登录", 0),
    AlreadyExists("1005", "已存在", 0),
    AlreadyLocked("1006", "已锁定", 0),
    LockFailure("1007", "锁定异常", 0),
    DbFailure("1008", "数据库异常", 0),
    NetworkFailure("1009", "网络异常", 0),
    AdaptorFailure("1010", "外部接口异常", 0),
    ServerBusy("1012", "服务器忙", 0);

    private String code;
    private String message;
    private int args;

    @Override
    public String getCode() {
        return this.code;
    }

    @Override
    public String getDescription() {
        return this.message;
    }

    private CommonResponseCode(String code, String message, int args) {
        this.code = code;
        this.message = message;
        this.args = args;
    }
}

public interface IErrorMessage {

    String getCode();

    String getDescription();

}

  

@ApiModel("通用响应体")
@Schema(name = "通用响应体")
public class ResultResponse <T>{


    @ApiModelProperty(
            value = "业务请求id",
            example = "ucenter-xxxxxxx"
    )
    private String requestId;

    @ApiModelProperty(
            value = "业务错误码",
            example = "1001"
    )
    private String code;

    @ApiModelProperty("额外消息")
    private String message;

    @ApiModelProperty("是否成功")
    private Boolean success;

    @ApiModelProperty("一些meta信息,例如需要crsf的token")
    private Map<String, Object> meta;

    @ApiModelProperty("实际数据")
    private T Data;

    public ResultResponse() {
        this.requestId = UUID.randomUUID().toString();
    }

    public ResultResponse(String reqId) {
        this.requestId = reqId;
    }

    public ResultResponse(String reqId, T payload) {
        this.requestId = reqId;
        this.code = "";
        this.Data = payload;
        this.success = true;
    }

    public ResultResponse(String reqId, String code, String msg) {
        this.requestId = reqId;
        this.code = code;
        this.message = msg;
        this.success = true;
    }

    public ResultResponse(String reqId, String code, String msg, T data) {
        this.requestId = reqId;
        this.code = code;
        this.message = msg;
        this.Data = data;
        this.success = true;
    }

    public static <T> ResultResponse<T> succResult() {
        ResultResponse<T> resultResponse = new ResultResponse();
        resultResponse.setCode(CommonResponseCode.Success.getCode());
        resultResponse.setSuccess(true);
        resultResponse.setMessage("success");
        return resultResponse;
    }

    public static <T> ResultResponse<T> succResult(T data) {
        ResultResponse<T> resultDTO = new ResultResponse();
        resultDTO.setCode(CommonResponseCode.Success.getCode());
        resultDTO.setSuccess(true);
        resultDTO.setMessage("success");
        resultDTO.setData(data);
        return resultDTO;
    }

    public static <T> ResultResponse<T> succResult(String reqId, T data) {
        ResultResponse<T> resultResponse = new ResultResponse();
        resultResponse.setRequestId(reqId);
        resultResponse.setCode(CommonResponseCode.Success.getCode());
        resultResponse.setSuccess(true);
        resultResponse.setMessage("success");
        resultResponse.setData(data);
        return resultResponse;
    }

    public static <T> ResultResponse<T> errorResult(String message) {
        return errorResult("500", message);
    }

    public static <T> ResultResponse<T> errorResult(String code, String message) {
        ResultResponse<T> resultDTO = new ResultResponse();
        resultDTO.setCode(code);
        resultDTO.setMessage(message);
        resultDTO.setSuccess(false);
        return resultDTO;
    }

    public static <T> ResultResponse<T> errorResult(String reqId, String code, String message) {
        ResultResponse<T> resultResponse = new ResultResponse();
        resultResponse.setRequestId(reqId);
        resultResponse.setCode(code);
        resultResponse.setMessage(message);
        resultResponse.setSuccess(false);
        return resultResponse;
    }

    public static <T> ResultResponse<T> errorResult(String reqId, String code, String message, T data) {
        ResultResponse<T> resultResponse = new ResultResponse();
        resultResponse.setRequestId(reqId);
        resultResponse.setCode(code);
        resultResponse.setMessage(message);
        resultResponse.setSuccess(false);
        resultResponse.setData(data);
        return resultResponse;
    }


    public static <T> ResultResponse<T> notFound(String message) {
        return errorResult("404", message);
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this);
    }

    public String getRequestId() {
        return this.requestId;
    }

    public String getCode() {
        return this.code;
    }

    public String getMessage() {
        return this.message;
    }

    public Boolean getSuccess() {
        return this.success;
    }

    public Map<String, Object> getMeta() {
        return this.meta;
    }

    public T getData() {
        return this.Data;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public void setMeta(Map<String, Object> meta) {
        this.meta = meta;
    }

    public void setData(T Data) {
        this.Data = Data;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof ResultResponse)) {
            return false;
        } else {
            ResultResponse<?> other = (ResultResponse)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                Object this$requestId = this.getRequestId();
                Object other$requestId = other.getRequestId();
                if (this$requestId == null) {
                    if (other$requestId != null) {
                        return false;
                    }
                } else if (!this$requestId.equals(other$requestId)) {
                    return false;
                }

                Object this$code = this.getCode();
                Object other$code = other.getCode();
                if (this$code == null) {
                    if (other$code != null) {
                        return false;
                    }
                } else if (!this$code.equals(other$code)) {
                    return false;
                }

                Object this$message = this.getMessage();
                Object other$message = other.getMessage();
                if (this$message == null) {
                    if (other$message != null) {
                        return false;
                    }
                } else if (!this$message.equals(other$message)) {
                    return false;
                }

                label62: {
                    Object this$success = this.getSuccess();
                    Object other$success = other.getSuccess();
                    if (this$success == null) {
                        if (other$success == null) {
                            break label62;
                        }
                    } else if (this$success.equals(other$success)) {
                        break label62;
                    }

                    return false;
                }

                label55: {
                    Object this$meta = this.getMeta();
                    Object other$meta = other.getMeta();
                    if (this$meta == null) {
                        if (other$meta == null) {
                            break label55;
                        }
                    } else if (this$meta.equals(other$meta)) {
                        break label55;
                    }

                    return false;
                }

                Object this$Data = this.getData();
                Object other$Data = other.getData();
                if (this$Data == null) {
                    if (other$Data != null) {
                        return false;
                    }
                } else if (!this$Data.equals(other$Data)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(Object other) {
        return other instanceof ResultResponse;
    }


}
public enum UserEnum {

    // 常量数据
    SUCCESS(1000, "处理成功", "通用"),
    ERROR(1001, "处理失败", "通用"),
    LOGIN_ERROR(1002, "登录失败", "登录操作"),
    REG_SUCCESS(1003, "注册成功", "注册操作"),
    REG_ERROR(1004, "注册失败", "注册操作");

    // 常量数据对应的参数信息
    // 编码
    private final int code;
    // 提示信息
    private final String msg;
    // 操作类型
    private final String type;

    // 带参的构造函数,参数类型要与常量数据中的数据类型顺序一致
    UserEnum(int code, String msg, String type) {
        this.code = code;
        this.msg = msg;
        this.type = type;
    }

    /**
     * <h5>功能:将当前常量数据转化为JSON信息</h5>
     *
     * @return
     */
    public String toJson() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", this.code);
        jsonObject.put("msg", this.msg);
        jsonObject.put("type", this.type);
        return jsonObject.toJSONString();
    }

    /**
     * 根据code获取msg
     */
    public static String getValue(int code) {
        for (UserEnum toolStatusCodeExt : values()) {
            if (code == toolStatusCodeExt.code) {
                return toolStatusCodeExt.msg;
            }
        }
        return "";
    }

    /**
     * <h5>功能:获取当前枚举类常量信息</h5>
     */
    private static List<String> getArgs() {
        List<String> list = new ArrayList<>();
        for (UserEnum toolStatusCodeExt : values()) {
            list.add(toolStatusCodeExt.name());
        }
        return list;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public String getType() {
        return type;
    }



}

controller包下内容:

@Slf4j
@Validated
@RestController
@RequestMapping("/v1/user")
public class UserController {



    @Autowired
    UserService userService;


    @PostMapping("/add")
    public ResultResponse<Integer> add(@RequestBody User user) {
        return  ResultResponse.succResult(userService.add(user));
    }

    @PostMapping("/update")
    public ResultResponse<Boolean> update(@RequestBody User user) {
        return  ResultResponse.succResult(userService.updateUser(user));
    }


    @GetMapping ("/getUser")
    public ResultResponse<User> getUser(@Valid @NotBlank(message = "用户ID不能为空") String id) {
        return  ResultResponse.succResult(userService.getUser(id));
    }

    @GetMapping ("/queryPageUser")
    public ResultResponse<PageInfo<User>> queryPageUser(Integer pageNumber,Integer pageSize) {
        return  ResultResponse.succResult(userService.queryPageUser(pageNumber,pageSize));
    }

    @GetMapping ("/deleteById")
    public ResultResponse<Integer> deleteById(@Valid @NotBlank(message = "用户ID不能为空") String id) {
        return  ResultResponse.succResult(userService.deleteById(id));
    }

}

service包下内容

@Service
public interface UserService extends IService<User> {

    int add(User user);

    boolean updateUser(User user);

    User getUser(String id);

    PageInfo<User> queryPageUser(Integer pageNumber, Integer pageSize);

    int deleteById(String id);
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Autowired
    private ApplicationContext applicationContext;


    @Autowired
    private UserMapper userMapper;

    @Override
    public int add(User user) {

       return userMapper.insert(user);
    }

    @Override
    public boolean updateUser(User user) {
      return  userMapper.updateUser(user);

    }

    @Override
    public User getUser(String id) {
        return userMapper.selectById(id);
    }

    @Override
    public PageInfo<User> queryPageUser(Integer pageNumber, Integer pageSize) {
        PageHelper.startPage(pageNumber, pageSize);
        List<User> list = userMapper.selectList(null);
        return new PageInfo<>(list);
    }

    @Override
    public int deleteById(String id) {
        return userMapper.deleteById(id);
    }
}



 pojo包下内容:

@Data
@ToString
@TableName("user")
public class User implements Serializable {

    @TableId(type = IdType.AUTO)
    private Integer id;

    private String name;

    private Integer age;

    private String email;

}

  mapper包下内容:

@Mapper
public interface UserMapper extends BaseMapper<User> {

    boolean updateUser(User user);
}

   mapper文件下内容:

<?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.zigao.com.mapper.UserMapper">
    <update id="updateUser">
        update user set
                          name  =#{name},
                          age=#{age},
                          email =#{email}
        where id=#{id}
    </update>
</mapper>

  启动类:


@SpringBootApplication
@MapperScan("com.zigao.com.mapper")
public class ZiGaoApplication {
    public static void main(String[] args) {
            SpringApplication.run(ZiGaoApplication.class, args);

        }
    }


sql语句:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `name` varchar(55) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
  `age` int(0) NULL DEFAULT NULL COMMENT '年龄',
  `email` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL COMMENT '邮箱',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 117 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

启动项目:

启动成功:

我们调用postman实现CRUD:

 添加:

添加成功:

 数据库多了条记录

 update: 注意了 update我没有用原声方法,因为如果有Integer类型的话,我要更新成null的话,就更新不了(后续我会专门写一篇文章)文章地址:mybatis-plus Integer类型null值无法修改的问题_因努力 果随缘的博客-优快云博客

id为1更新前的数据 

id为1更新后的数据 

 

查询:根据id查询:

分页查询: 

根据ID刪除:

 好了,crud基本完成了,大家有啥问题随时问,或者有啥错误随时指出,我们一起进步!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值