从01开始 从01开始
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)

peterjxl

人生如逆旅,我亦是行人
首页
  • 计算机科学导论
  • 数字电路
  • 计算机组成原理

    • 计算机组成原理-北大网课
  • 操作系统
  • Linux
  • Docker
  • 计算机网络
  • 计算机常识
  • Git
  • JavaSE
  • Java高级
  • JavaEE

    • Ant
    • Maven
    • Log4j
    • Junit
    • JDBC
    • XML-JSON
  • JavaWeb

    • 服务器软件
    • Servlet
  • Spring
  • 主流框架

    • Redis
    • Mybatis
    • Lucene
    • Elasticsearch
    • RabbitMQ
    • MyCat
    • Lombok
  • SpringMVC
  • SpringBoot
  • 学习网课的心得
  • 输入法
  • 节假日TodoList
  • 其他
  • 关于本站
  • 网站日记
  • 友人帐
  • 如何搭建一个博客
GitHub (opens new window)
  • JavaSE

  • JavaSenior

  • JavaEE

  • JavaWeb

  • Spring

  • 主流框架

  • SpringMVC

  • SpringBoot

    • SpringBoot教程-尚硅谷

      • SpringBoot课程介绍
      • Spring和SpringBoot
      • HelloWorld
      • 了解自动配置原理
      • 底层注解-@Configuration详解
      • 底层注解-@Import导入组件
      • 底层注解-@Conditional条件装配
      • 原生配置文件引入-@ImportResource
      • 底层注解-配置绑定@ConfigurationProperties
      • 自动配置原理
      • 自动配置流程
      • Lombok简化开发
      • DevTools
      • Spring-Initailizr
      • 配置文件-Yaml用法
      • Web开发简介
      • web开发-静态资源规则于定制化
      • 静态资源配置原理
      • Rest映射及源码解析
      • 请求映射原理
      • 常用参数注解使用
      • MatrixVariable:矩阵变量
      • 各种类型参数解析原理
      • Servlet-API参数解析原理
      • Model、Map参数解析原理
      • 自定义对象参数绑定原理
      • 自定义Converter原理
      • 数据响应原理
      • 内容协商原理
      • 基于请求参数的内容原理
      • 自定义MessageConverter原理
      • Thymeleaf初体验
      • web实验-后台管理系统
      • web实验-抽取公共页面
      • web实验-遍历数据
      • 源码分析-视图解析器与视图
      • 拦截器-登录检查与静态资源放行
      • 拦截器的执行时机和原理
      • 单文件和多文件上传的使用
      • 文件上传原理
      • 错误处理机制
      • 错误处理-底层组件源码分析
      • 异常处理流程
      • 几种异常处理原理
      • Web原生对象注入
      • 嵌入式Servlet容器
      • 定制化原理
      • 数据库场景的自动配置分析和整合测试
      • 自定义方式整合Druid
      • 通过starter整合Druid
      • 整合Mybatis
      • 使用注解整合Mybatis
      • 整合MybatisPlus操作数据库
        • 什么是Mybatis-Plus
        • MybatisX 插件
        • 需求
        • 数据库准备
        • 修改表单
        • 引入依赖
        • 自动配置
        • 修改User类
        • 准备Mapper
        • 源码
      • MybatisPlus-列表分页展示
      • 整合Redis
      • 单元测试-Junit5
      • 单元测试-断言机制
      • 单元测试-前置条件
      • 单元测试-嵌套测试
      • 单元测试-参数化测试
      • 指标监控-基本概念
      • 指标监控-配置EndPoint
      • 指标监控-可视化
      • 原理解析-Profile功能
      • 配置文件深入
      • 自定义Starter
      • SpringApplication初始化过程
      • SpringBoot完整启动过程
      • SpringBoot
  • Java并发

  • Java源码

  • JVM

  • 韩顺平

  • Java
  • Java
  • SpringBoot
  • SpringBoot教程-尚硅谷
2023-08-22
目录

整合MybatisPlus操作数据库

# 530.整合MybatisPlus操作数据库

本节课我们来学习整合Mybatis-Plus,完成基本的查询功能   ‍

# 什么是Mybatis-Plus

Mybatis-Plus是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

官网:MyBatis-Plus (opens new window),GitHub地址:github.com/baomidou/mybatis-plus (opens new window)

‍

# MybatisX 插件

官网文档:MybatisX快速开发插件 | MyBatis-Plus (opens new window)

MybatisX 是一款基于 IDEA 的快速开发插件,为效率而生。

安装方法:打开 IDEA,进入 File -> Settings -> Plugins -> Browse Repositories,输入 mybatisx​ 搜索并安装。

‍

其功能丰富,例如可以通过Mapper接口,跳转到XML:

​​mybatisx-jump​​

‍

还有生成代码、重置模板、智能提示等功能,更多内容请看文档。

‍

# 需求

接下来我们使用Mybatis-Plus,来完成动态表格中数据的显示(从数据库中读取并显示):

​​

‍

为此,我们先学习下如何使用Mybatis-Plus,下节课再开始做修改

‍

ps:我们在学习异常处理的时候,手动给/dynamic_table​请求抛出了一个异常

‍

public class TableController {
 
    @GetMapping("/dynamic_table")
    public String dynamic_table(Model model){
        List<User> users = Arrays.asList(new User("zhangsan", "123456"),
                new User("lisi", "123444"),
                new User("haha", "aaaaa"),
                new User("hehe", "aaddd"));
        model.addAttribute("users", users);

        if (users.size() > 3){
            throw new UserTooManyException();
        }

        return "table/dynamic_table";
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

这里我们删除抛出异常相关代码:

‍

‍

‍

# 数据库准备

根据MyBatis-Plus 快速入门文档 (opens new window),我们准备下数据库

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id BIGINT(20) AUTO_INCREMENT NOT NULL COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    PRIMARY KEY (id)
);


DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

‍

# 修改表单

‍

先删除掉无用的表格,例如下面的“DATATABLES HIDDEN ROW DETAILS EXAMPLE”

​​

‍

对应的代码在dynamic_table.html,我们直接删除其外层的div(class=row的div):

​​

‍

‍

# 引入依赖

根据Mybatis文档,引入:

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

‍

可以分析下其依赖:

​​

‍

可以看到引入了不少和数据源开发相关的,因此我们可以注释掉我们之前配置的这依赖:

<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-jdbc</artifactId>-->
<!--        </dependency>-->

<!--        <dependency>-->
<!--            <groupId>org.mybatis.spring.boot</groupId>-->
<!--            <artifactId>mybatis-spring-boot-starter</artifactId>-->
<!--            <version>2.1.4</version>-->
<!--        </dependency>-->
1
2
3
4
5
6
7
8
9
10

​​

‍

# 自动配置

我们看看Mybatis-Plus自动配置了什么,首先打开spring.factories​:

​

‍

其内容:

# Auto Configure
org.springframework.boot.env.EnvironmentPostProcessor=\
  com.baomidou.mybatisplus.autoconfigure.SafetyEncryptProcessor
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.baomidou.mybatisplus.autoconfigure.MybatisPlusLanguageDriverAutoConfiguration,\
  com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
1
2
3
4
5
6

‍

我们打开MybatisPlusAutoConfiguration​:

@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnSingleCandidate(DataSource.class)
@EnableConfigurationProperties({MybatisPlusProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class, MybatisPlusLanguageDriverAutoConfiguration.class})
public class MybatisPlusAutoConfiguration implements InitializingBean{
    //......
}
1
2
3
4
5
6
7
8

‍

首先,其配置是绑定了MybatisPlusProperties​,配置项开头是mybatis-plus​:

@Data
@Accessors(chain = true)
@ConfigurationProperties(prefix = Constants.MYBATIS_PLUS)
public class MybatisPlusProperties {

 
    private String configLocation;

    private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};

    //..............
1
2
3
4
5
6
7
8
9
10
11

可以看到mapperLocations是有默认值的

‍

还自动配置了SqlSessionFactory​,用的是容器中的数据源,并且会读取全局配置文件(如有)并加载:

@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
    factory.setDataSource(dataSource);
    factory.setVfs(SpringBootVFS.class);
    if (StringUtils.hasText(this.properties.getConfigLocation())) {
        factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
    }
    //...........
1
2
3
4
5
6
7
8
9
10

‍

‍

还自动配置了SqlSessionTemplate​:

@Bean
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    ExecutorType executorType = this.properties.getExecutorType();
    if (executorType != null) {
        return new SqlSessionTemplate(sqlSessionFactory, executorType);
    } else {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
1
2
3
4
5
6
7
8
9
10

‍

‍

还配置了扫描@Mapper​注解的类:

@Configuration
@Import(AutoConfiguredMapperScannerRegistrar.class)
@ConditionalOnMissingBean({MapperFactoryBean.class, MapperScannerConfigurer.class})
public static class MapperScannerRegistrarNotFoundConfiguration implements InitializingBean {

    @Override
    public void afterPropertiesSet() {
        logger.debug(
            "Not found configuration for registering mapper bean using @MapperScan, MapperFactoryBean and MapperScannerConfigurer.");
    }
}
1
2
3
4
5
6
7
8
9
10
11

‍

# 修改User类

由于我们已经有User类了,但是没有id、name属性,我们可以修改User,增加属性:

package com.peterjxl.learnspringbootwebadmin.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class User implements Serializable {
    private String userName;
    private String password;

    // 以下是数据库的字段
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

‍

但是Mybatis-Plus中,默认是认为所有类的成员变量,都是在数据库存在的,如果不存在则需要额外指出:

    @TableField(exist = false)
    private String userName;
  
    @TableField(exist = false)
    private String password;
1
2
3
4
5

‍


此外,默认会通过类名去找数据库中同名的表,但如果数据库表名和类名不同,要如何绑定呢?使用注解@TableName​

@TableName("新表名")
public class User implements Serializable {
//............
1
2
3

‍

‍

‍

# 准备Mapper

之前我们是自己写SQL(不管是配置文件还是使用注解),而Mybatis-Plus不用了,我们只需继承一个类:​BaseMapper​

package com.peterjxl.learnspringbootwebadmin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.peterjxl.learnspringbootwebadmin.bean.User;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> { }
1
2
3
4
5
6
7
8

‍

该类已经帮我们写好了一大堆方法:

public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);
    int deleteById(Serializable id);
    int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
    int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
    int updateById(@Param(Constants.ENTITY) T entity);
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
    T selectById(Serializable id);
    List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
    List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
    T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    //...............
1
2
3
4
5
6
7
8
9
10
11
12
13
14

‍

‍

接下来,我们测试下,在测试类新增如下代码:

class LearnSpringBootWebAdminApplicationTests {
    @Autowired
    UserMapper userMapper;
  
    @Test
    void testUserMapper() {
        log.info("用户信息:{}", userMapper.selectById(1L));
    }
}
1
2
3
4
5
6
7
8
9

‍

‍

‍

运行结果:

用户信息:User(userName=null, password=null, id=1, name=Jone, age=18, email=test1@baomidou.com)
1

‍

# 源码

已将本文源码上传到Gitee (opens new window)或GitHub (opens new window) 的分支demo14,读者可以通过切换分支来查看本文的示例代码

在GitHub上编辑此页 (opens new window)
上次更新: 2023/8/23 10:10:57
使用注解整合Mybatis
MybatisPlus-列表分页展示

← 使用注解整合Mybatis MybatisPlus-列表分页展示→

Theme by Vdoing | Copyright © 2022-2023 粤ICP备2022067627号-1 粤公网安备 44011302003646号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式