SpringBoot数据访问——整合MybatisPlus

SpringBoot数据访问——整合MybatisPlus

0.MybatisPlus简介

官方介绍: MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

官方文档:MybatisPlus官方文档 写得很好很详细!

1.导入依赖

maven工程pom.xml文件下,导入以下依赖:

 <!--        Web模块-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--        MySQL驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--        Lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--        mybatis-plus 启动器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>

2.配置数据连接

数据源使用默认的,数据库配置如下:

默认的application.properties

#mysql配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://*.*.*.*:3306/springboot_demo
spring.datasource.username=账号
spring.datasource.password=密码

yml格式:

#配置数据源
spring:
  datasource:
    username: 账号
    password: 密码
    url: jdbc:mysql://*.*.*.*:3306/springboot_demo
    driver-class-name: com.mysql.jdbc.Driver

3.初始化测试数据表

这里就用了一个简单了表,包含id(主键且自增),english,chinese这三个字段。

初始化测试数据表

4.使用MybatisPlus操作数据

4.1.编写数据库中表对应的实体类Bean

entity包下建立word类:

package com.piao.springboot_mybatisplus.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Word {
    private Integer id;
    private String english;
    private String chinese;
}

这里使用了Lombok插件中的注解 @Data

  • @Data注解在类自动生成setter/getter、equals、canEqual、hashCode、toString方法,如为final属性,则不会为该属性生成setter方法。
  • @AllArgsConstructor 所有参数的构造方法

4.2 编写mapper接口

使其继承自BaseMapper,泛型为实体类Word。这样就拥有了基本的CRUD和分页功能。

package com.piao.springboot_mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.piao.springboot_mybatisplus.entity.Word;

//接口继承自BaseMapper  泛型为实体类Word;这样就具备通用的一些CRUD操作了
public interface WordMapper extends BaseMapper<Word> {
}

4.3 查看BaseMapper接口源码

这里我备注了一些注释,便于理解

public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);//插入数据,参数泛型,为任意实体类

    int deleteById(Serializable id);//根据id删除

    int deleteByMap(@Param("cm") Map<String, Object> columnMap);//更具map中的条件,批量删除

    int delete(@Param("ew") Wrapper<T> wrapper);//根据条件构造器删除

    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);//根据id批量删除

    int updateById(@Param("et") T entity);//更新数据,参数泛型,为任意实体类

    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);//根据条件构造器更新

    T selectById(Serializable id);//根据id查询

    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);//根据id批量查询

    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);//根据columnMap条件查询

    T selectOne(@Param("ew") Wrapper<T> queryWrapper);//根据条件构造器查询

    Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);//根据条件构造器查询,返回查询总记录数

    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);//根据条件构造器查询,list形式返回,条件构造器为空则查询所有。

    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);//根据条件构造器查询,List<Map<String, Object>>形式返回

    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);//根据条件构造器查询,只返回第一个字段的值

    <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);//根据实体类条件,分页查询全部记录

    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);// 根据条件构造器,分页查询全部记录
}

4.4 编写控制器实现基本CRUD

功能包括基本的CRUD操作:

  • 添加单词信息
  • 根据id查询单词信息
  • 根据id更新单词信息
  • 根据id删除单词信息
  • 查询所有单词
   @Resource
   private WordMapper wordMapper;

将业务对象WordMapper注入后便可直接使用自带的CRUD方法操作数据。

这里加了详细且原始的数据校验判空处理,当然有更优雅的方式…这里就不展开了。

推荐这位大佬的博客:啥?听说你还在手写复杂的参数校验?

package com.piao.springboot_mybatisplus.controller;

import com.piao.springboot_mybatisplus.entity.Word;
import com.piao.springboot_mybatisplus.mapper.WordMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TestController {
    //存储预返回页面的结果对象
    private Map<String, Object> result;
    //注入业务对象
    @Resource
    private WordMapper wordMapper;

    //添加单词信息
    @PostMapping("/insertWord")
    @ResponseBody
    public Map<String, Object> insertWord(Word word) {
        result = new HashMap<>();

        //数据校验 判空!
        if (null == word) {
            result.put("message", "插入的单词为空");
            return result;
        }
        if (null == word.getChinese() || "".equals(word.getEnglish())) {
            result.put("message", "插入的单词中文为空或者为空字符串");
            return result;
        }
        if (null == word.getChinese() || "".equals(word.getChinese())) {
            result.put("message", "插入的单词中文为空或者为空字符串");
            return result;
        }
        wordMapper.insert(word);
        result.put("message", "插入单词成功");
        return result;
    }

    //根据id查询单词信息
    @GetMapping("/getWordById")
    @ResponseBody
    public Map<String, Object> getWordById(Integer id) {
        result = new HashMap<>();

        //数据校验 判空!
        if (null == id) {
            result.put("message", "传入id为空");
            return result;
        }

        result.put("word",wordMapper.selectById(id));
        result.put("message", "查询单词成功");
        return result;
    }


    //根据id更新单词信息
    @PostMapping("/updateWordById")
    @ResponseBody
    public Map<String, Object> updateWordById(Integer id, String english, String chinese) {
        result = new HashMap<>();

        //数据校验 判空!
        if (null == id) {
            result.put("message", "更新的单词id为空");
            return result;
        }
        if (null == english || "".equals(english)) {
            result.put("message", "更新的单词中文为空或者为空字符串");
            return result;
        }
        if (null == chinese || "".equals(chinese)) {
            result.put("message", "更新的单词中文为空或者为空字符串");
            return result;
        }
        wordMapper.updateById(new Word(id, english, chinese));
        result.put("message", "更新单词成功");
        return result;
    }

    //根据id删除单词信息
    @PostMapping("/deleteWordById")
    @ResponseBody
    public Map<String, Object> deleteWordById(Integer id) {
        result = new HashMap<>();
        //数据校验 判空!
        if (null == id) {
            result.put("message", "输入的单词id为空");
            return result;
        }
        wordMapper.deleteById(id);
        result.put("message", "删除单词成功");
        return result;
    }

    //查询所有单词
    @GetMapping("/getAllWord")
    @ResponseBody
    public Map<String, Object> getAllWord() {
        result = new HashMap<>();

        //selectList(null)设置过滤条件为空,就是查询所有,并以list形式返回
        result.put("word",wordMapper.selectList(null));
        result.put("message", "查询所有单词成功");
        return result;
    }
}

其中wordMapper.selectList(null),条件构造器参数传null,就是查询所有,并以List集合(泛型为实体类Word)的形式返回。

发布了83 篇原创文章 · 获赞 40 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_42391904/article/details/104346730