對狂神說的MybatisPlus的學習總結


1.什么是MybatisPlus?

需要的基礎:spring,spring mvc,mybatis
作用:可以節省大量的工作時間,所有的CRUD代碼都可以自動完成,簡化Mybatis
MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window) 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。

MybatisPlus官網

特性

  • 無侵入:只做增強不做改變,引入它不會對現有工程產生影響,如絲般順滑
  • 損耗小:啟動即會自動注入基本 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 操作智能分析阻斷,也可自定義攔截規則,預防誤操作

2.快速入門

步驟:
1.導入對應的依賴
2.研究依賴如何配置
3.代碼如何編寫
4.提高擴展技術能力

根據官方文檔開始入門
快速開始

2.1創建數據庫(我創建的就是命名MybatisPlus數據庫)

2.2創建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)
);

真實開發中這些字段也是必不可少的,version(樂觀鎖),deleted(邏輯刪除),gmt_create,gmt_modified

插入數據

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');

2.3編寫項目,初始化項目,初始化一個springboot項目

2.4導入依賴

<!--        數據庫驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
<!--mybatis_plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.7</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

2.5 連接數據庫

#mysql  5
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# mysql 8 驅動不同 com.mysql.cj.jdbc.Driver . 需要增加時區的配置 serverTimezone=GMT%2B8

2.6使用mybatis_plus

  • pojo
  • mapper接口
  • 使用

User類的編寫

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

UserMapper的編寫

//在對應的Mapper上面實現基本的接口BaseMapper
@Repository//代表持久層
public interface UserMapper extends BaseMapper<User> {
//    所有的CRUD操作編寫完成
//    不需要和原來一樣寫一大堆的文件了
}

在應用添加mapperscan掃描

@SpringBootApplication
@MapperScan("cn.dzp.mapper")
public class MybatisPlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }

}

測試類編寫

@Autowired
    private UserMapper userMapper;
    @Test
    void contextLoads() {
//        參數是Wrapper,條件構造器,暫時先不用
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
//        for (User user : users) {
//            System.out.println(user);
//        }
    }

查詢所有用戶

3.配置日志

我們所有的sql現在是不可見的,我們希望知道它是這么執行的,所以我們必須要看日志

配置日志

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

配置完成日志后,后面的學習就需要注意這個自動生成的sql,就會喜歡上myabatis-plus!

4.CRUD基本操作

4.1插入功能

編寫測試代碼

    @Test
    public void testInsert(){
        User user = new User();
        user.setName("鄧瘋子");
        user.setAge(20);
        user.setEmail("2601920751@qq.com");

        int insert = userMapper.insert(user);
        System.out.println(insert);
        System.out.println(user);
    }

運行查看發現我並沒有設置ID,但是它幫我自動生成了ID,現在來研究下自動生成ID

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

4.2主鍵生成策略

snowflake是Twitter開源的分布式ID生成算法,結果是一個long型的ID。其核心思想是:使用41bit作為毫秒數,10bit作為機器的ID(5個bit是數據中心:北京,上海,5個bit的機器ID),12bit作為毫秒內的流水號(意味着每個節點在每毫秒可以產生 4096 個 ID),最后還有一個符號位,永遠是0。具體實現的代碼可以參看https://github.com/twitter/snowflake。雪花算法支持的TPS可以達到419萬左右(2^22*1000)。

雪花算法在工程實現上有單機版本和分布式版本。單機版本如下,分布式版本可以參看美團leaf算法:https://github.com/Meituan-Dianping/Leaf

  • redis
  • zookeeper

主鍵自增
1.實體類上

@TableId(type = IdType.AUTO)
    private Long id;

其余的源碼解釋

    AUTO(0),//自增
    NONE(1),//未設置主鍵
    INPUT(2),//手動輸入,需要自己配置id
    ID_WORKER(3),//默認的全局唯一id
    UUID(4),//全球唯一id
    ID_WORKER_STR(5);//ID_WORKER字符串表示

2.數據庫字段一定要自增

在進行插入測試,完成自增

4.3 測試更新

編寫測試代碼

 @Test
    public void testUpdate(){
        User user = new User();
        user.setId(1400650930251329539L);
        user.setName("鄧瘋子很菜");
        int i = userMapper.updateById(user);
        System.out.println(i);
    }

查看日志

所有的sql都是自動幫你動態配置的

4.4自動填充

創建時間,修改時間,這些操作一般都是自動化完成的,不希望手動更新
比如數據表:gmt_create,gmt_modified,幾乎所有的表都要配置上,便於追蹤

方式一:數據庫級別(工作中不允許你修改數據庫的)
1.在表中新增字段create_time,update_time,兩個字段都需要current_timestamp更新

2.再次測試插入方法,需要先把實體類同步

    private Date createTime;
    private Date updateTime;

可以看到已經更新了,時間也自動更新

方式二:代碼級別
1.刪除數據庫的默認值,更新操作

2.實體類字段屬性上需要增加注釋

//    字段添加填充內容
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

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

3.編寫處理器處理這個注解即可!

package cn.dzp.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;

@Component
@Slf4j
 public class MyMetaObjectHandler implements MetaObjectHandler {
//    插入時候的填充策略
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill......");
//        String fieldName, Object fieldVal, MetaObject metaObject
        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);
    }
}

測試插入

查看數據庫

測試更新

查看數據庫,只更新了更新的時間

4.5 樂觀鎖

樂觀鎖: 顧名思義十分樂觀,他總是認為不會出現問題,無論干什么都不去上鎖!如果出現了問題,再次更新值測試
悲觀鎖;顧名思義十分悲觀,他總是認為出現問題,無論干什么都會上鎖!再去操作!

這里主要講解:樂觀鎖機制
樂觀鎖實現方式:

  • 取出記錄時,獲取當前version
  • 更新時,帶上這個version
  • 執行更新時,set version = newVersion where version = oldVersion
  • 如果version不對,就更新失敗

測試一下MP(MybatisPlus簡寫)的樂觀鎖插件

1.給數據庫加上version字段

2.我們實體類增加對應的字段

@Version//代表這是一個樂觀鎖的注解
   private Integer version;

3.注冊組件

package cn.dzp.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@MapperScan("cn.dzp.mapper")
@EnableTransactionManagement
@Configuration//配置類
public class MybatisPlusConfig {
//    注冊樂觀鎖插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }
}

4.測試樂觀鎖成功

//    測試樂觀鎖成功
    @Test
    public void testOptimisticLocker(){
//        1.查詢用戶信息
        User user = userMapper.selectById(1L);
//        2.修改用戶信息
        user.setName("樂觀鎖");
        user.setEmail("leguansuo.com");
//        3.更新操作
        userMapper.updateById(user);
    }


5.測試樂觀鎖失敗

//    測試樂觀鎖失敗!多線程下
@Test
public void testOptimisticLocker2(){
//        線程1
    User user1 = userMapper.selectById(1L);
    user1.setName("樂觀鎖111");
    user1.setEmail("leguansuo111.com");

//    模擬線程2執行了插隊操作
    User user2 = userMapper.selectById(1L);
    user2.setName("樂觀鎖222");
    user2.setEmail("leguansuo222.com");
    userMapper.updateById(user2);


    userMapper.updateById(user1);//沒有樂觀鎖就會覆蓋插隊線程的值
}

4.6查詢操作

//測試查詢
    @Test
    public void testSelectById(){
        User user = userMapper.selectById(1L);
        System.out.println(user);
    }
//    測試批量查詢
    @Test
    public void testSelectBatchId(){
        List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3, 4, 5));
        users.forEach(System.out::println);
    }
    @Test
//    條件查詢之一 map
    public void testSelectByBatchIds(){
        HashMap<String, Object> map = new HashMap<>();
//        自定義查詢
        map.put("name","鄧瘋子");
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);
    }

4.7 分頁查詢

1.原始的limit分頁
2.pageHelper第三方插件
3.Mp內置了分頁插件

如何使用
1.配置攔截器組件即可

// 舊版分頁插件
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

2.測試分頁查詢

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

        page.getRecords().forEach(System.out::println);
    }

4.8 邏輯刪除

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

測試:
1.在數據庫表中增加一個deleted字段

2.實體類中增加屬性

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

3.配置

//注冊邏輯刪除
    @Bean
    public ISqlInjector sqlInjector(){
        return new LogicSqlInjector();
    }

配置文件配置

配置邏輯刪除

mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

4.測試刪除
雖然走的是刪除操作,但看日志文件可以發現是一個更新的操作

數據庫里依舊存在,但是deleted值變化成1

試試能不能查詢出來剛剛刪除的用戶

根據圖展示,並沒有查詢到此用戶,並且查詢動態拼接了一個條件(deleted=0)

以上CRUD操作及其擴展操作,我們必須精通掌握!會大大提高你的工作和寫項目的效率的!

5.性能分析插件

我們在平時的開發中,會遇到一些慢sql.

MP也提供了性能分析插件,如果超過這個時間就停止運行!
1.導入插件
(記得到配置文件里配置dev環境或者test環境)

#設置開發環境
spring.profiles.active=dev
@Bean
    @Profile({"dev","test"}) //設置dev 和 test環境開啟,保證效率
    public PerformanceInterceptor performanceInterceptor(){
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(100);//ms 設置sql執行的最大時間,如果超過了則不執行
        performanceInterceptor.setFormat(true);//是否格式化
        return performanceInterceptor;
    }

2.測試查詢

 @Test
    void contextLoads() {
//        參數是Wrapper,條件構造器,暫時先不用
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
//        for (User user : users) {
//            System.out.println(user);
//        }
    }


可以看到執行時間沒有超過我們設置的100ms,所以執行成功

使用性能分析插件 ,可以幫助我們提高效率!

6.條件構造器

十分重要:Wrapper

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

編寫新的測試類WrapperTest

package cn.dzp;

import cn.dzp.mapper.UserMapper;
import cn.dzp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class WrapperTest {

    @Autowired
    private UserMapper userMapper;
    @Test
    void contextLoads() {
//        測試一:查詢name不為空的用戶,並且郵箱不為空的用戶,年齡大於等於20
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .isNotNull("name")
                .isNotNull("email")
                .ge("age",20);//可以鏈式編程
        userMapper.selectList(wrapper).forEach(System.out::println);
    }

    @Test
    void test2(){
        //查詢名字等於鄧瘋子
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name","鄧瘋子");
        System.out.println(userMapper.selectOne(wrapper));//查詢一個數據,查詢多個使用map或者list
    }

    @Test
    void test3(){
//        查詢年齡在20-30之間的用戶
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.between("age",20,30);
        System.out.println(userMapper.selectCount(wrapper));
    }

    @Test
    void test4(){
//        模糊查詢
        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        左和右  %test和test%
        wrapper
                .notLike("name","鄧")
                .likeRight("email","test")
        ;
        userMapper.selectMaps(wrapper).forEach(System.out::println);
    }

    @Test
    void test5(){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
//        id在子查詢中查出來
        wrapper.inSql("id","select id from user where id<3 ");

        userMapper.selectObjs(wrapper).forEach(System.out::println);
    }
//測試6
    @Test
    void tesy6(){
//通過id進行排序
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        userMapper.selectList(wrapper).forEach(System.out::println);
    }
}

7.代碼自動生成器(非常強大)

dao、pojo、service、controller都給我自己去編寫完成!
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、
Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發效率。

7.1 添加依賴

MyBatis-Plus 從 3.0.3 之后移除了代碼生成器與模板引擎的默認依賴,需要手動添加相關依賴:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.0.7</version>
</dependency>

7.2 添加依賴添加 模板引擎 依賴,MyBatis-Plus 支持 Velocity(默認)、Freemarker、Beetl,用戶可以選擇自己熟悉的模板引擎,如果都不滿足您的要求,可以采用自定義模板引擎。

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.3</version>
        </dependency>

7.3編寫代碼自動生成器類

package cn.dzp;

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 FengCode {
    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("鄧瘋子");
        gc.setOpen(false);
        gc.setFileOverride(false);//是否覆蓋
        gc.setServiceName("%sService");//去Service的I前綴
        gc.setIdType(IdType.ID_WORKER);//新版本ID_WORKER過時了,3.3.0后用ASSIGN_ID
        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");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

//        3.包的配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("AutoGenerator");
        pc.setParent("cn.dzp");
        pc.setEntity("pojo");
        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("gmt_create", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("gmt_modified", 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();//執行
    }
}

運行查看結果,可以看到我們設置的文件夾都被自動生成了,成功自動生成

但是可以看到實體類user中報紅,這是因為我們設置了 gc.setSwagger2(true),所以需要Swagger2的依賴,但是pom沒有導入依賴,所以報錯,導入下依賴就好

對應依賴如下

<!-- https://mvnrepository.com/artifact/io.swagger/swagger-annotations -->
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.6.2</version>
        </dependency>

在查看項目發現報紅消失,問題完美解決

至此代碼自動生成器部分完結

大家喜歡的可以去B站給狂神哥點波關注或者三連,他的java個人感覺講的非常好滴!

本人關於狂神的MybatisPlus的總結與學習到這結束了

看到最后的大佬們幫忙點個推薦,謝謝,這個對我真的很重要!


免責聲明!

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



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