MyBatisPlus笔记

news2024/9/22 15:46:55

一、MyBatisPlus概述


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

MyBatis-Plus可以节省我们大量工作时间,所有的CRUD代码它都可以自动化完成!

同类技术框架有:JPA、tk-mapper、MyBatis-Plus。

MyBatisPlus官网地址:https://mybatis.plus/、https://baomidou.com/

MyBatisPlus项目地址:https://gitee.com/baomidou/mybatis-plus

在这里插入图片描述

在这里插入图片描述


MyBatisPlus特性:

  • 无侵入:只做增强不做改变,不会对现有工程产生影响。
  • 损耗小:启动即会自动注入基本 CRUD(增删改查),性能基本无损耗,直接面向对象操作。
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表CRUD 操作,更有强大的条件构造器(QueryWrapper),满足各类使用需求。
  • 支持 Lambda:编写查询条件无需担心字段写错。
  • 支持主键自动生成:支持多达4种主键策略(内含分布式唯一ID生成器:Sequence)可自由配置,完美解决主键问题。
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作。
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )。
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用。
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询。
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库。
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询。
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作。

MyBatisPlus支持的数据库:(任何能使用MyBatis进行CRUD操作,并且支持标准 SQL 的数据库)

  • mysql 、mariadb 、oracle 、db2 、h2 、hsql 、sqlite 、postgresql 、sqlserver 、presto 、Gauss 、Firebird。

  • Phoenix 、clickhouse 、Sybase ASE 、 OceanBase 、达梦数据库 、虚谷数据库 、人大金仓数据库 、南大通用数据库。


MyBatisPlus框架结构:

在这里插入图片描述


二、MP快速入门


文档地址:https://mybatis.plus/guide/quick-start.html

使用第三方组件的流程:
1、导入对应的依赖。
2、研究依赖如何配置。
3、代码如何编写。
4、提高扩展技术能力!


SpringBoot整合MP操作步骤如下:

1、准备数据:

create database if not exists mp_db character set utf8;
use mp_db;
CREATE TABLE user (
            id bigint(20) primary key auto_increment,
            name varchar(32) not null,
            password  varchar(32) not null,
            age int(3) not null ,
            tel varchar(32) not null
);
insert into user values(null,'tom','123456',12,'12345678910');
insert into user values(null,'jack','123456',8,'12345678910');
insert into user values(null,'jerry','123456',15,'12345678910');
insert into user values(null,'tom','123456',9,'12345678910');
insert into user values(null,'snake','123456',28,'12345678910');
insert into user values(null,'张益达','123456',22,'12345678910');
insert into user values(null,'张大炮','123456',16,'12345678910');

在这里插入图片描述


2、创建一个maven工程。

3、导入依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.baidou</groupId>
    <artifactId>mp01_quickstart</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!--父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!-- lombok,通过注解简化实体类的开发 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- mybatisplus的起步依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        
        <!-- Junit起步依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>

在这里插入图片描述
在这里插入图片描述


4、编写实体类:(类名与表名对应,属性名与字段名对应)(ORM对象关系映射)

package com.baidou.entity;

import lombok.Data;
//实体类
@Data
public class User {
    private Long id;
    private String name;
    private String password;
    private Integer age;
    private String tel;
}

5、在application.yml文件中配置jdbc相关参数:

# 配置数据源
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/mp_db?useSSL=false
    username: root
    password: 123456

# 配置日志级别为:debug (输出大于等于debug级别的日志信息)
logging:
  level:
    com.baidou: debug

# mp配置
mybatis-plus:
  configuration:
    # 配置标准sql输出
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl    

在这里插入图片描述


6、定义mapper接口,继承BaseMapper。

package com.baidou.mapper;

import com.baidou.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

//在对应的Mapper上面继承BaseMapper接口

//@Repository //代表持久层
@Mapper
public interface UserMapper extends BaseMapper<User> {
    //所有的CRUD操作都已经编写完成了
    //你不需要像以前配置一大堆文件了!
}

在这里插入图片描述


7、定义启动类,并配置mapper扫描:

package com.baidou;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.baidou.mapper") //扫描我们的mapper包下的所有接口 
public class MyBatisPlusApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyBatisPlusApplication.class, args);
    }
}

8、编写测试

package com.baidou.test;

import com.baidou.entity.User;
import com.baidou.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * 测试类
 *
 * @author 白豆五
 * @version 2023/1/23
 * @since JDK8
 */
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testFindAll() {
        List<User> userList = userMapper.selectList(null); //null表示不传条件参数
        for (User user : userList) {
            System.out.println(user);
        }
    }
}

运行结果:

在这里插入图片描述

灵活拷问:

  • SQL谁帮我们写的? MyBatisPlus都写好了。
  • 方法哪里来的? MyBatisPlus都写好了。

三、标准数据层开发


1. MyBatisPlus的CRUD操作


功能之前自定义的接口MP提供的接口
新增boolean save(T entity)int insert(T entity)
删除boolean delete(int id)int deleteById(Serializable id)
修改boolean update(T entity)int updateById(T entity)
根据id查询T getById(int id)T selectById(Serializable id)
查询全部List getAll()List selectList()
分页查询PageInfo getAll(int age,int size)IPage selectPage(IPage page)
按条件查询List getAll(Condition condition)IPage selectPage(Wrapper queryWrapper)

示例代码:

package com.baidou.test;

import com.baidou.entity.User;
import com.baidou.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * 测试mapper接口的crud操作
 *
 * @author 白豆五
 * @version 2023/1/23
 * @since JDK8
 */
@SpringBootTest
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    // 查询全部
    @Test
    public void testFindAll() {
        List<User> userList = userMapper.selectList(null); //null表示不传条件参数
        for (User user : userList) {
            System.out.println(user);
        }
    }

    // 新增
    @Test
    public void testSave() {
        User user = new User();
        user.setName("小舞");
        user.setAge(18);
        user.setPassword("123456");
        user.setTel("13212341234");

        int num = userMapper.insert(user);

        if (num==1){
            System.out.println("添加成功");

            //自动返回新增记录的主键
            Long id = user.getId();
            System.out.println("用户的id:"+id);//1617500546355167234
        }
    }

    // 修改
    @Test
    public void testUpdate() {
        User user = new User();
        user.setId(5L);
        user.setName("小米");
        userMapper.updateById(user);
    }


    // 删除
    @Test
    public void testDelete() {
        userMapper.deleteById(1527307439025266690L);
    }
}

2. MyBatisPlus分页功能


MyBatisPlus内置分页插件。

2.1 MyBatisPlus分页功能接口


// 分页查询
IPage<T> selectPage(IPage<T> page)

2.2 MyBatisPlus分页使用


1、配置分页拦截器组件

package com.baidou.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *MybatisPlus的配置类
 * @author 白豆五
 * @version 2023/1/23
 * @since JDK8
 */

@Configuration
public class MybatisPlusConfig {

    // 注册分页插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        //1 创建MybatisPlusInterceptor拦截器对象
        MybatisPlusInterceptor mpInterceptor=new MybatisPlusInterceptor();
        //2 添加分页拦截器
        mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        
        //注意:不同的数据库在开启分页功能的时候,需要设置成对应的数据库类型 (数据库方言不太一样)
        //mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mpInterceptor;
    }
}

在这里插入图片描述


2、开启MyBatisPlus日志

# 开启mp的sql日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3、编写测试

// 分页查询
@Test
public void testSelectPage() {
    // 1.创建IPage分页对象,设置分页参数
    // 参数一:当前页
    // 参数二: 页面大小
    IPage<User> page = new Page<>(1, 3);//import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

    // 2.执行分页查询
    userMapper.selectPage(page, null);

    // 3.获取分页结果
    System.out.println("当前页码值:" + page.getCurrent());
    System.out.println("每页显示数:" + page.getSize());
    System.out.println("总页数:" + page.getPages());
    System.out.println("总条数:" + page.getTotal());
    System.out.println("当前页数据:" + page.getRecords());
}

运行结果:

在这里插入图片描述


解决日志打印过多问题

1、取消初始化spring日志打印

在这里插入图片描述

解决方案:在resources下新建一个logback.xml文件,名称固定,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

</configuration>

logback常用配置:https://www.jianshu.com/p/75f9d11ae011


2、关闭springboot启动的beanner图标

spring:
  main:
    banner-mode: off # 关闭SpringBoot启动图标(banner)

3、关闭MybatisPlus启动的beanner图标

mybatis-plus:
  global-config:
    banner: off # 关闭mybatisplus启动图标

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/177116.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

leetcode1143 最长公共子序列

题目 给定两个字符串 text1 和 text2&#xff0c;返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 &#xff0c;返回 0 。 一个字符串的 子序列 是指这样一个新的字符串&#xff1a;它是由原字符串在不改变字符的相对顺序的情况下删除某些字符&#xff08;…

因果诊断原理

因果分析在近十来年逐渐倍受关注&#xff0c;其提供了解释因子间因果性的定量分析工具&#xff0c;广泛用于数据分析领域&#xff0c;同时也就用决策分析、作用预估等反事实因果推理中。本文首先对比了因果性和相关性的关系&#xff0c;之后确定因果关系的基本方法&#xff0c;…

博客搭建教程1-Archlinux环境配置

文章目录1 前言2 archlinux镜像下载3 archlinux安装1 前言 这个教程主要讲解linux环境下博客的搭建&#xff0c;这里的linux系统选择archlinux&#xff0c;博客的框架基于hexo框架。 参考博客&#xff1a; 1、ArchLinux安装教程 2、Archlinux2022年7月镜像 手把手安装教程 UE…

MySQL进阶——存储过程

MySQL 存储过程 1、简介 大多数 SQL 语句都是针对一个或多个表的单条语句。并非所有的操作都那么简单。经常会有一个完整的操作需要多条语句才能完成。 存储过程简单来说&#xff0c;就是为以后的使用而保存的一条或多条 MySQL 语句的集合。可将其视为批处理文件。虽然他们的…

【Spring(八)】带你打通Spring的注解开发

文章目录注解开发注解开发定义bean纯注解开发注解开发bean作用范围与生命周期管理注解开发依赖注入注解开发管理第三方bean注解开发实现为第三方bean注入资源总结注解开发 Spring的配置我们已经告一段落了&#xff0c;那接下来我们就要发挥Spring的强项了&#xff1a;简化开发&…

MySQL —— 数据库基础

目录 一、数据库的基本概念 1. 什么是数据库 2. 主流的数据库 二、基本使用 1. 连接服务器 2. 服务器管理 3. 服务器、数据库、表关系 4. 使用案例 5. 数据库的存储逻辑 三、MySQL架构 四、SQL分类 五、存储引擎 1. 存储引擎 2. 查看存储引擎 3. 存储引擎对比 …

Elasticsearch 这篇还不够吗

系列文章目录 文章目录系列文章目录一、概述1. ES 的基本概念2. ES 和关系型数据库的对比二、环境准备1. linux 下单机安装三、入门操作1. 创建索引2. 写入文档3. 根据id搜索文档4. 根据一般字段搜索文档5. 根据文本字段搜索文档四、ES 客户端实战1. Spring Data Elasticsearch…

学习shell与shell编程 vi与vim

Linux配置文件都是以ASCII的纯文本形式存在。 为什么学习vi 1)UnixLike系统都会内置vi文本编辑器&#xff0c;其他的文本编辑器则不一定存在 2)许多软件的编辑接口都会主动调用vi 3)vi具有程序编辑的能力&#xff0c;可以主动以字体颜色辨别语法的正确性 4)程序简单&#…

webgl纹理贴图机制

文章目录前言纹理图片大小规范纹理坐标系统贴图流程JavaScript部分齐次坐标—uv坐标数据准备加载外部纹理图像纹理配置加载着色器部分顶点着色器片元着色器完整示例使用多张纹理着色器接受两个纹理单元封装纹理配置赋值函数完整示例总结前言 在计算机图形学中&#xff0c;为了…

HTML+CSS+JS制作炫酷【烟花特效】

文章目录制作炫酷烟花特效一、普通烟花(分散形)HTML代码CSS代码JS代码二、圆形烟花HTML代码CSS代码JS代码三、爱心形烟花HTML代码CSS代码JS代码四、源码获取在线下载制作炫酷烟花特效 &#x1f4a1;本篇内容使用htmlcssjs制作鼠标点击出现烟花效果&#xff0c;分别介绍了分散型…

python-测试代码

1. 测试函数get_name.pydef combination(first, last):将姓名组合在一起name first lastreturn name.title()hello_world.pyfrom get_name import combinationprint("Enter q to quit!") while True:first input(Please input your first name: )if first q:b…

理光Aficio MP C2500扫描到文件夹设置方法

首先在需要接收扫描文件的电脑上设置共享文件夹。 注&#xff1a; &#xff08;1&#xff09;文件夹的名字最好简单一点&#xff0c;比如&#xff1a;scan、123等等&#xff1b; &#xff08;2&#xff09;文件夹的共享权限最好能设置为最大&#xff08;WindowsXP、Windows200…

Future、CompletableFuture概述

1.同步和异步 &#xff08;1&#xff09;同步&#xff1a;需要等待结果返回&#xff0c;才能继续运行 &#xff08;2&#xff09;异步&#xff1a;不需要等待结果返回&#xff0c;就能继续运行 &#xff08;3&#xff09;异步设计&#xff1a;多线程可以让方法执行变为异步(比…

第四章必备前端基础知识-第二节3:CSS盒模型和浮动

文章目录一&#xff1a;盒模型&#xff08;1&#xff09;border&#xff08;2&#xff09;padding&#xff08;3&#xff09;margin二&#xff1a;flex布局一&#xff1a;盒模型 盒模型&#xff1a;在HTML中&#xff0c;每个标签&#xff08;或元素&#xff09;相当于是一个盒…

Mybatis和Jpa

这里写目录标题1.Mybatis1.1 JDBC的缺点1.2 Mybatis的整体架构1.3 入门案例1.3.1 问题:无法连接到数据库服务器1.4 动态代理实现Mapper1.5 mybatis-config.xml配置1.5.1 properties属性读取外部资源1.5.2 settings设置1.5.3 typeAliases1.5.4 typeHandlers&#xff08;类型处理…

【Substance Designer】基础操作和节点学习记录

写在前面 这个记录稍微有点杂&#xff0c;大概是庄懂的技术美术入门课(美术向)-直播录屏-第20课和一些基础操作的记录合集吧&#xff01; 补充 学习发现&#xff0c;基础的节点是需要学习和记录的&#xff0c;但是真正用起来还是要多用多练&#xff01;所以这种简单的记录节点…

YOLOv5/v7 引入 RepVGG 重参数化模块

本篇博文代码出自YOLOv5-lite &#xff0c;YOLOv5-lite的作者在CSDN的账号是 pogg_ &#xff0c;大家可以关注一下&#xff0c;这也是一位在开源项目上做了很多工作的博主。 RepVGG的原理和融合推导过程可以看我的这篇博文&#xff1a;RepVGG&#xff1a;让VGG风格的ConvNets再…

机制设计原理与应用(三)Screening

文章目录3 Screening3.1 为单个不可分割的项目定价3.1.1 对θ\thetaθ的假设3.1.2 问题描述3.1.3 特性3.2 为无限可分的项目定价3.2.1 对θ\thetaθ的假设3.2.3 特性3.2.4 收益最大化3.2.5 最优解决方案3 Screening Screening theory&#xff1a;机制设计理论可以被看作是其多…

Cadence PCB仿真使用Allegro PCB SI生成振铃ringing仿真报告及报告导读图文教程

🏡《Cadence 开发合集目录》   🏡《Cadence PCB 仿真宝典目录》 目录 1,概述2,生成报告3,报告导读4,总结1,概述 本文简单介绍使用Allegro PCB SI生成网络的振铃性能评估的报告的方法,及振铃ringing报告要点导读。 2,生成报告 第1步,选择需要生成报告的网络,然后…

第二章 ArcGIS数据和地理数据库

文章目录第一节 ArcGIS和4D数据基本知识1 4D数据介绍1.1 DLG1.2 DEM1.3 DOM1.4 DRG1.5 4D表现2 ArcGIS的数据和4D数据对应3 栅格数据3.1 查看帮助3.2 空间分辨率3.3 分辨率与比例尺换算3.4 栅格数据介绍——cellsize3.5 栅格数据波段3.6 栅格格式4 栅格数据改变分辨率5 转换栅格…