趕緊收藏吧!MyBatis-Plus萬字長文圖解筆記,錯過了這個村可就沒這個店了


簡介

MyBatis-Plus(簡稱 MP)是一個 MyBatis的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生

願景

我們的願景是成為 MyBatis 最好的搭檔,就像 魂斗羅 中的 1P、2P,基友搭配,效率翻倍。

特性

  • 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
  • 損耗小:啟動即會自動注入基本 CURD,性能基本無損耗,直接面向對象操作
  • 強大的 CRUD 操作:內置通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求
  • 支持 Lambda 形式調用:通過 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作

框架結構

快速入門

  • 創建數據庫表(mybatis——plus)

  • 創建user表**

DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) 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)
);
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');  

  • 編寫項目,初始化項目!使用SpringBoot初始化!

  • 導入依賴

<!-- 數據庫驅動 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<!-- 只用mybatis-plus即可,不用再導入mybatis -->
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.0.5</version>
</dependency>

  • yml文件中配置數據庫**
spring:
  datasource:
    password: 123456
    username: root
    url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.jdbc.Driver

  • 編寫pojo類,mapper接口**

  • pojo

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

  • mapper接口,繼承BaseMapper

    @Repository //代表是持久層
    public interface UserMapper extends BaseMapper<User> {
        //里面不需要寫東西
    }
    
    
  • 啟動類添加mapper掃描

    @MapperScan("com.alan.mybatis.plus.mapper")
    
    
  • 在測試類中測試

    @SpringBootTest
    class MybatisPlusApplicationTests {
        @Autowired
        private UserMapper userMapper;
    
        @Test
        void contextLoads() {
            //查詢
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        }
    
    }
    
    
  • 結果

  • 添加日志

  • 配置yml

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
    
  • 結果

CRUD擴展

插入操作

Insert插入

@Test
public void testInsert(){
    User user = new User();
    user.setName("圖靈");
    user.setAge(20);
    user.setEmail("123345567@qq.com");
    //result是影響行數
    int result = userMapper.insert(user);
    System.out.println(result);
    //會自動id回填,默認雪花算法
    System.out.println(user);
}

數據庫插入的id的默認值為:全局的唯一的id

主鍵生成策略

1、雪花算法:

snowflake是Twitter開源的分布式ID生成算法,結果是一個long型的ID。其核心思想是:使用41bit作為
毫秒數,10bit作為機器的ID(5個bit是數據中心,5個bit的機器ID),12bit作為毫秒內的流水號(意味
着每個節點在每毫秒可以產生 4096 個 ID),最后還有一個符號位,永遠是0。可以保證幾乎全球唯
一!

2、主鍵自增

2.1 需要在實體類字段上添加@TableId(type = IdType.AUTO)

2.2 數據庫對應的字段一定要是自增的

2.3結果

其他的源碼解釋

public enum IdType {
    AUTO(0),//數據庫id自增
    NONE(1),//未設置主鍵
    INPUT(2),//手動輸入
    ID_WORKER(3),//默認的全局唯一id
    UUID(4),//全局唯一id uuid
    ID_WORKER_STR(5);//ID_WORKER 字符串表示法 
}

更新操作


@Test
public void testUpdate(){
    User user = new User();
    user.setId(1334744418774695938L);
    //這里只改年齡
    user.setAge(19);
    int i = userMapper.updateById(user);
    System.out.println(i);
}

更新操作是動態SQL

自動填充


創建時間、修改時間!這些個操作一遍都是自動化完成的,我們不希望手動更新!
阿里巴巴開發手冊:所有的數據庫表:gmt_create、gmt_modified幾乎所有的表都要配置上!而且需要自動化!

代碼級別

  • 修改數據庫

  • 修改實體類,在時間屬性上添加注解
Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;

    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date UpdateTime;
}

@TableField(fill = FieldFill.INSERT) 在創建新這條數據時,更新時間。

@TableField(fill = FieldFill.INSERT_UPDATE),在創建和更新這條數據時,更新時間。

  • 編寫配置類

    @Slf4j
    @Component //該注解時把該類添加到IOC容器中
    public class MyMetaObjectHandler implements MetaObjectHandler {
        //插入時的策略
        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("start insert fill.....");
            this.setFieldValByName("createTime",new Date(),metaObject);
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
        //更新時的策略
        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("start update fill.....");
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
    }
    
    

分別運行添加和修改,結果:

分頁查詢

1、編寫配置類,攔截器

package com.alan.mybatis.plus.config;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * @Author Alan Ture
 * @Description
 */
@Configuration
public class MyBatisPlusConfig {
    /**
     * 分頁插件
      */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

}

2、直接使用Page對象即可。

//分頁測試查詢
@Test
public void testPage(){
    // 參數一:當前頁
    // 參數二:頁面大小
    Page<User> page = new Page<>(1,5);
    userMapper.selectPage(page,null);
    page.getRecords().forEach(System.out::println);
    System.out.println(page.getTotal());
}

刪除操作

1、根據id刪除記錄

// 測試刪除
@Test
public void testDeleteById(){
    userMapper.deleteById(1334744418774695938L);
}

// 通過id批量刪除
@Test
public void testDeleteBatchId(){
    userMapper.deleteBatchIds(Arrays.asList(1334745985150111745L,1334745985150111746L));
}
// 通過map刪除
@Test
public void testDeleteMap() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("name", "圖靈");
    userMapper.deleteByMap(map);
}

邏輯刪除

物理刪除 :從數據庫中直接移除
邏輯刪除 :再數據庫中沒有被移除,而是通過一個變量來讓他失效! deleted = 0 => deleted = 1

1、數據庫添加字段

2、實體類添加字段,並添加注解

@TableLogic//邏輯刪除
private Integer deleted;

3、配置類配置

// 邏輯刪除組件!
@Bean
public ISqlInjector sqlInjector() {
    return new LogicSqlInjector();
}

4、yml配置(刪除為0,沒有刪除為1)

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      logic-delete-value: 0
      logic-not-delete-value: 1

5、測試刪除

// 測試刪除
@Test
public void testDeleteById(){
    userMapper.deleteById(1L);
}

實際走的是更新操作

結果

性能分析插件

我們在平時的開發中,會遇到一些慢sql。測試! druid,
作用:性能分析攔截器,用於輸出每條 SQL 語句及其執行時間
MP也提供性能分析插件,如果超過這個時間就停止運行!

1、導入插件(記住,要在SpringBoot中配置環境為dev或者 test 環境! )

properties.yml設置開發環境

spring:
  profiles:
    active: dev

/**
  * SQL執行效率插件
  * 設置 dev test 環境開啟,保證我們的效率
  */
@Bean
@Profile({"dev","test"})
public PerformanceInterceptor performanceInterceptor() {
    PerformanceInterceptor performanceInterceptor = new
        PerformanceInterceptor();
    // ms設置sql執行的最大時間,如果超過了則不執行
    performanceInterceptor.setMaxTime(10);
    // 是否格式化代碼
    performanceInterceptor.setFormat(true);
    return performanceInterceptor;
}

2、測試使用(超過規定時間會報異常)

條件構造器 Wrapper

我們寫一些復雜的sql就可以使用它來替代!

1、測試一,isNotNull不為空,ge大於等於

@Test
public void contextLoads() {
// 查詢name不為空的用戶,並且郵箱不為空的用戶,年齡大於等於12
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
            .isNotNull("name")
            .isNotNull("email")
            .ge("age",20);
    userMapper.selectList(wrapper).forEach(System.out::println);
    // 和我們剛才學習的map對比一下

}

2、測試二,eq查詢相等數據

@Test
public void test2(){
    // 查詢名字Jone
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("name","Jone");
    User user = userMapper.selectOne(wrapper);
    // 查詢一個數據,出現多個結果使用List或者 Map
    System.out.println(user);
}

代碼自動生成器

package com.alan.mybatis.plus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;

// 代碼自動生成器
public class GenCode {
    public static void main(String[] args) {
// 需要構建一個 代碼自動生成器 對象
        AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("Alan Ture");
        gc.setOpen(false);
        gc.setFileOverride(false); // 是否覆蓋
        gc.setServiceName("%sService"); // 去Service的I前綴
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);
//2、設置數據源
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
//3、包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("blog");
        pc.setParent("com.alan");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);
//4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user"); // 設置要映射的表名
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true); // 自動lombok;
        strategy.setLogicDeleteFieldName("deleted");
// 自動填充配置
        TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("update_time",
                FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate);
        tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);
// 樂觀鎖
//        strategy.setVersionFieldName("version");
//        strategy.setRestControllerStyle(true);
//        strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
        mpg.setStrategy(strategy);
        mpg.execute(); //執行
    }
}

最后

最后提供免費的Java架構學習資料,學習技術內容包含有:Spring,Dubbo,MyBatis, RPC, 源碼分析,高並發、高性能、分布式,性能優化,微服務 高級架構開發等等。歡迎關注我的公眾號:前程有光獲取!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM