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

簡介

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

願景java

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

特性

  • 無侵入:只作加強不作改變,引入它不會對現有工程產生影響,如絲般順滑
  • 損耗小:啓動即會自動注入基本 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、DB二、H二、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掃描spring

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

    @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

主鍵生成策略

一、雪花算法:apache

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

二、主鍵自增性能優化

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

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

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);
        }
    }
分別運行添加和修改,結果:

分頁查詢

一、編寫配置類,攔截器
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();
    }

}
二、直接使用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());
}

刪除操做

一、根據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

一、數據庫添加字段

二、實體類添加字段,並添加註解

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

三、配置類配置

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

四、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

五、測試刪除

// 測試刪除
@Test
public void testDeleteById(){
    userMapper.deleteById(1L);
}
實際走的是更新操做

結果

性能分析插件

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

一、導入插件(記住,要在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;
}

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

條件構造器 Wrapper

咱們寫一些複雜的sql就可使用它來替代!

一、測試一,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對比一下

}

二、測試二,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();
// 配置策略
// 一、全局配置
        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);
//二、設置數據源
        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);
//三、包的配置
        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);
//四、策略配置
        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, 源碼分析,高併發、高性能、分佈式,性能優化,微服務 高級架構開發等等。歡迎關注個人公衆號:前程有光獲取!

相關文章
相關標籤/搜索