mybatis plus

簡介

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

我們的願景是成爲Mybatis最好的搭檔,就像 Contra Game 中的1P、2P,基友搭配,效率翻倍。

特性

  • 無侵入:Mybatis-Plus 在 Mybatis 的基礎上進行擴展,只做增強不做改變,引入 Mybatis-Plus 不會對您現有的 Mybatis 構架產生任何影響,而且 MP 支持所有 Mybatis 原生的特性
  • 依賴少:僅僅依賴 Mybatis 以及 Mybatis-Spring
  • 損耗小:啓動即會自動注入基本CURD,性能基本無損耗,直接面向對象操作
  • 預防Sql注入:內置Sql注入剝離器,有效預防Sql注入攻擊
  • 通用CRUD操作:內置通用 Mapper、通用 Service,僅僅通過少量配置即可實現單表大部分 CRUD 操作,更有強大的條件構造器,滿足各類使用需求
  • 多種主鍵策略:支持多達4種主鍵策略(內含分佈式唯一ID生成器),可自由配置,完美解決主鍵問題
  • 支持ActiveRecord:支持 ActiveRecord 形式調用,實體類只需繼承 Model 類即可實現基本 CRUD 操作
  • 支持代碼生成:採用代碼或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 層代碼,支持模板引擎,更有超多自定義配置等您來使用(P.S. 比 Mybatis 官方的 Generator 更加強大!)
  • 支持自定義全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 支持關鍵詞自動轉義:支持數據庫關鍵詞(order、key……)自動轉義,還可自定義關鍵詞
  • 內置分頁插件:基於Mybatis物理分頁,開發者無需關心具體操作,配置好插件之後,寫分頁等同於普通List查詢
  • 內置性能分析插件:可輸出Sql語句以及其執行時間,建議開發測試時啓用該功能,能有效解決慢查詢
  • 內置全局攔截插件:提供全表 delete 、 update 操作智能分析阻斷,預防誤操作

代碼託管

Github|OSChina

參與貢獻

歡迎各路好漢一起來參與完善Mybatis-Plus,我們期待你的PR!

  • 貢獻代碼:代碼地址 Mybatis-Plus ,歡迎提交 Issue 或者 Pull Requests
  • 維護文檔:文檔地址 Mybatis-Plus-Doc ,歡迎參與翻譯和修訂

入門

快速開始
簡單示例(傳統)

假設我們已存在一張 User 表,且已有對應的實體類 User,實現 User 表的 CRUD 操作我們需要做什麼呢?

/** User 對應的 Mapper 接口 */
public interface UserMapper extends BaseMapper<User> { }
  • 1
  • 2

以上就是您所需的所有操作,甚至不需要您創建XML文件,我們如何使用它呢?

基本CRUD

// 初始化 影響行數
int result = 0;
// 初始化 User 對象
User user = new User();

// 插入 User (插入成功會自動回寫主鍵到實體類)
user.setName("Tom");
result = userMapper.insert(user);

// 更新 User
user.setAge(18);
result = userMapper.updateById(user);

// 查詢 User
User exampleUser = userMapper.selectById(user.getId());

// 查詢姓名爲‘張三’的所有用戶記錄
List<User> userList = userMapper.selectList(
        new EntityWrapper<User>().eq("name", "張三")
);

// 刪除 User
result = userMapper.deleteById(user.getId());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

以上是基本的 CRUD 操作,當然我們可用的 API 遠不止這幾個,我們提供了多達 17 個方法給大家使用,可以極其方便的實現單一、批量、分頁等操作,接下來我們就來看看 MP 是如何使用分頁的。

分頁操作

// 分頁查詢 10 條姓名爲‘張三’的用戶記錄
List<User> userList = userMapper.selectPage(
        new Page<User>(1, 10),
        new EntityWrapper<User>().eq("name", "張三")
);
  • 1
  • 2
  • 3
  • 4
  • 5

如您所見,我們僅僅需要繼承一個 BaseMapper 即可實現大部分單表 CRUD 操作,極大的減少的開發負擔。

有人也許會質疑:這難道不是通用 Mapper 麼?別急,咱們接着往下看。

現有一個需求,我們需要分頁查詢 User 表中,年齡在18~50之間性別爲男且姓名爲張三的所有用戶,這時候我們該如何實現上述需求呢?

傳統做法是 Mapper 中定義一個方法,然後在 Mapper 對應的 XML 中填寫對應的 SELECT 語句,且我們還要集成分頁,實現以上一個簡單的需求,往往需要我們做很多重複單調的工作,普通的通用 Mapper 能夠解決這類痛點麼?

用 MP 的方式打開以上需求

// 分頁查詢 10 條姓名爲‘張三’、性別爲男,且年齡在18至50之間的用戶記錄
List<User> userList = userMapper.selectPage(
        new Page<User>(1, 10),
        new EntityWrapper<User>().eq("name", "張三")
                .eq("sex", 0)
                .between("age", "18", "50")
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

以上操作,等價於

SELECT *
FROM sys_user
WHERE (name='張三' AND sex=0 AND age BETWEEN '18' AND '50')
LIMIT 0,10
  • 1
  • 2
  • 3
  • 4

Mybatis-Plus 通過 EntityWrapper(簡稱 EW,MP 封裝的一個查詢條件構造器)或者 Condition(與EW類似) 來讓用戶自由的構建查詢條件,簡單便捷,沒有額外的負擔,能夠有效提高開發效率。

簡單示例(ActiveRecord)

ActiveRecord 一直廣受動態語言( PHP 、 Ruby 等)的喜愛,而 Java 作爲準靜態語言,對於 ActiveRecord 往往只能感嘆其優雅,所以我們也在 AR 道路上進行了一定的探索,喜歡大家能夠喜歡,也同時歡迎大家反饋意見與建議。

我們如何使用 AR 模式?

@TableName("sys_user") // 註解指定表名
public class User extends Model<User> {

  ... // fields

  ... // getter and setter

  /** 指定主鍵 */
  @Override
  protected Serializable pkVal() {
      return this.id;
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

我們僅僅需要繼承 Model 類且實現主鍵指定方法 即可讓實體開啓 AR 之旅,開啓 AR 之路後,我們如何使用它呢?

基本CRUD

// 初始化 成功標識
boolean result = false;
// 初始化 User
User user = new User();

// 保存 User
user.setName("Tom");
result = user.insert();

// 更新 User
user.setAge(18);
result = user.updateById();

// 查詢 User
User exampleUser = t1.selectById();

// 查詢姓名爲‘張三’的所有用戶記錄
List<User> userList1 = user.selectList(
        new EntityWrapper<User>().eq("name", "張三")
);

// 刪除 User
result = t2.deleteById();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

分頁操作

// 分頁查詢 10 條姓名爲‘張三’的用戶記錄
List<User> userList = user.selectPage(
        new Page<User>(1, 10),
        new EntityWrapper<User>().eq("name", "張三")
).getRecords();
  • 1
  • 2
  • 3
  • 4
  • 5

複雜操作

// 分頁查詢 10 條姓名爲‘張三’、性別爲男,且年齡在18至50之間的用戶記錄
List<User> userList = user.selectPage(
        new Page<User>(1, 10),
        new EntityWrapper<User>().eq("name", "張三")
                .eq("sex", 0)
                .between("age", "18", "50")
).getRecords();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

AR 模式提供了一種更加便捷的方式實現 CRUD 操作,其本質還是調用的 Mybatis 對應的方法,類似於語法糖。

通過以上兩個簡單示例,我們簡單領略了 Mybatis-Plus 的魅力與高效率,值得注意的一點是:我們提供了強大的代碼生成器,可以快速生成各類代碼,真正的做到了即開即用。

安裝集成
依賴配置

查詢最高版本或歷史版本方式:Maven中央庫 | Maven阿里庫

如何集成

Mybatis-Plus 的集成非常簡單,對於 Spring,我們僅僅需要把 Mybatis 自帶的MybatisSqlSessionFactoryBean替換爲 MP 自帶的即可。

MP 大部分配置都和傳統 Mybatis 一致,少量配置爲 MP 特色功能配置,此處僅對 MP 的特色功能進行講解,其餘請參考 Mybatis-Spring 配置說明。

示例工程:

mybatisplus-spring-mvc

mybatisplus-spring-boot

PostgreSql 自定義 SQL 注入器 
sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector

示例代碼:

XML 配置

詳細配置可參考參數說明中的 MybatisSqlSessionFactoryBean 和 GlobalConfiguration

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
    <!-- 配置數據源 -->
    <property name="dataSource" ref="dataSource"/>
    <!-- 自動掃描 Xml 文件位置 -->
    <property name="mapperLocations" value="classpath:mybatis/*/*.xml"/>
    <!-- 配置 Mybatis 配置文件(可無) -->
    <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
    <!-- 配置包別名,支持通配符 * 或者 ; 分割 -->
    <property name="typeAliasesPackage" value="com.baomidou.springmvc.model"/>
    <!-- 枚舉屬性配置掃描,支持通配符 * 或者 ; 分割 -->
    <property name="typeEnumsPackage" value="com.baomidou.springmvc.entity.*.enums"/>

    <!-- 以上配置和傳統 Mybatis 一致 -->

    <!-- 插件配置 -->
    <property name="plugins">
        <array>
            <!-- 分頁插件配置, 參考文檔分頁插件部分!! -->
            <!-- 如需要開啓其他插件,可配置於此 -->
        </array>
    </property>

    <!-- MP 全局配置注入 -->
    <property name="globalConfig" ref="globalConfig"/>
</bean>

<!-- 定義 MP 全局策略 -->
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
    <!-- 主鍵策略配置 -->
    <!-- 可選參數
        AUTO->`0`("數據庫ID自增")
        INPUT->`1`(用戶輸入ID")
        ID_WORKER->`2`("全局唯一ID")
        UUID->`3`("全局唯一ID")
    -->
    <property name="idType" value="2"/>

    <!-- 數據庫類型配置 -->
    <!-- 可選參數(默認mysql)
        MYSQL->`mysql`
        ORACLE->`oracle`
        DB2->`db2`
        H2->`h2`
        HSQL->`hsql`
        SQLITE->`sqlite`
        POSTGRE->`postgresql`
        SQLSERVER2005->`sqlserver2005`
        SQLSERVER->`sqlserver`
    -->
    <property name="dbType" value="oracle"/>

    <!-- 全局表爲下劃線命名設置 true -->
    <property name="dbColumnUnderline" value="true"/>
</bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

特別注意 MybatisSqlSessionFactoryBean 非原生的類,必須如上配置 !

Java Config

優秀案例

核心功能

代碼生成器

在代碼生成之前,首先進行配置,MP提供了大量的自定義設置,生成的代碼完全能夠滿足各類型的需求,如果你發現配置不能滿足你的需求,歡迎提交issue和pull-request,有興趣的也可以查看源碼進行了解。

參數說明

參數相關的配置,詳見源碼

主鍵策略選擇

MP支持以下4中主鍵策略,可根據需求自行選用:

描述
IdType.AUTO數據庫ID自增
IdType.INPUT用戶輸入ID
IdType.ID_WORKER全局唯一ID,內容爲空自動填充(默認配置)
IdType.UUID全局唯一ID,內容爲空自動填充

AUTO、INPUT和UUID大家都應該能夠明白,這裏主要講一下ID_WORKER。首先得感謝開源項目Sequence,感謝作者李景楓。

什麼是Sequence?簡單來說就是一個分佈式高效有序ID生產黑科技工具,思路主要是來源於Twitter-Snowflake算法。這裏不詳細講解Sequence,有興趣的朋友請[點此去了解Sequence(http://git.oschina.net/yu120/sequence)。

MP在Sequence的基礎上進行部分優化,用於產生全局唯一ID,好的東西希望推廣給大家,所以我們將ID_WORDER設置爲默認配置。

表及字段命名策略選擇

在MP中,我們建議數據庫表名採用下劃線命名方式,而表字段名採用駝峯命名方式。

這麼做的原因是爲了避免在對應實體類時產生的性能損耗,這樣字段不用做映射就能直接和實體類對應。當然如果項目裏不用考慮這點性能損耗,那麼你採用下滑線也是沒問題的,只需要在生成代碼時配置dbColumnUnderline屬性就可以。

如何生成代碼 
方式一、代碼生成

<!-- 模板引擎 -->
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.0</version>
</dependency>

<!-- MP 核心庫 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>最新版本</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

代碼生成、示例一

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
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.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

/**
 * <p>
 * 代碼生成器演示
 * </p>
 */
public class MpGenerator {

    /**
     * <p>
     * MySQL 生成演示
     * </p>
     */
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir("D://");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);// 不需要ActiveRecord特性的請改爲false
        gc.setEnableCache(false);// XML 二級緩存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
    // .setKotlin(true) 是否生成 kotlin 代碼
        gc.setAuthor("Yanghu");

        // 自定義文件命名,注意 %s 會自動填充表實體屬性!
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sDao");
        // gc.setServiceName("MP%sService");
        // gc.setServiceImplName("%sServiceDiy");
        // gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);

        // 數據源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert(){
            // 自定義數據庫表字段類型轉換【可選】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                System.out.println("轉換類型:" + fieldType);
        // 注意!!processTypeConvert 存在默認類型轉換,如果不是你要的效果請自定義返回、非如下直接返回。
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("521");
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8");
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
    // strategy.setCapitalMode(true);// 全局大寫命名 ORACLE 注意
        strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此處可以修改爲您的表前綴
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        // strategy.setInclude(new String[] { "user" }); // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定義實體父類
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // 自定義實體,公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定義 mapper 父類
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定義 service 父類
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定義 service 實現類父類
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定義 controller 父類
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【實體】是否生成字段常量(默認 false)
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【實體】是否爲構建者模型(默認 false)
        // public User setName(String name) {this.name = name; return this;}
        // strategy.setEntityBuilderModel(true);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.baomidou");
        pc.setModuleName("test");
        mpg.setPackageInfo(pc);

        // 注入自定義配置,可以在 VM 中使用 cfg.abc 【可無】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        // 自定義 xxList.jsp 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/template/list.jsp.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸入文件名稱
                return "D://my_" + tableInfo.getEntityName() + ".jsp";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

    // 調整 xml 生成目錄演示
         focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 關閉默認 xml 生成,調整生成 至 根目錄
        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);

        // 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內容修改,
        // 放置自己項目的 src/main/resources/templates 目錄下, 默認名稱一下可以不配置,也可以自定義模板名稱
        // TemplateConfig tc = new TemplateConfig();
        // tc.setController("...");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
    // 如上任何一個模塊如果設置 空 OR Null 將不生成該模塊。
        // mpg.setTemplate(tc);

        // 執行生成
        mpg.execute();

        // 打印注入設置【可無】
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154

代碼生成、示例二

new AutoGenerator().setGlobalConfig(
    ...
).setDataSource(
    ...
).setStrategy(
    ...
).setPackageInfo(
    ...
).setCfg(
    ...
).setTemplate(
    ...
).execute();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

其他方式、 Maven插件生成

待補充(Maven代碼生成插件 待完善) http://git.oschina.net/baomidou/mybatisplus-maven-plugin

通用 CRUD
簡單介紹

實體無註解化設置,表字段如下規則,主鍵叫 id 可無註解大寫小如下規則。

1、駝峯命名 【 無需處理 】

2、全局配置: 下劃線命名 dbColumnUnderline 設置 true , 大寫 isCapitalMode 設置 true

註解說明

表名註解 @TableName

  • com.baomidou.mybatisplus.annotations.TableName
描述
value表名( 默認空 )
resultMapxml 字段映射 resultMap ID

主鍵註解 @TableId

  • com.baomidou.mybatisplus.annotations.TableId
描述
value字段值(駝峯命名方式,該值可無)
type主鍵 ID 策略類型( 默認 INPUT ,全局開啓的是 ID_WORKER )

字段註解 @TableField

  • com.baomidou.mybatisplus.annotations.TableField
描述
value字段值(駝峯命名方式,該值可無)
el是否爲數據庫表字段( 默認 true 存在,false 不存在 )
exist是否爲數據庫表字段( 默認 true 存在,false 不存在 )
strategy字段驗證 ( 默認 非 null 判斷,查看 com.baomidou.mybatisplus.enums.FieldStrategy )
fill字段填充標記 ( 配合自動填充使用 )

序列主鍵策略 註解 @KeySequence

  • com.baomidou.mybatisplus.annotations.KeySequence
描述
value序列名
clazzid的類型

樂觀鎖標記註解 @Version

  • com.baomidou.mybatisplus.annotations.Version
條件構造器

實體包裝器,用於處理 sql 拼接,排序,實體參數查詢等!

補充說明: 使用的是數據庫字段,不是Java屬性!

實體包裝器 EntityWrapper 繼承 Wrapper

  • 例如:
  • 翻頁查詢
public Page<T> selectPage(Page<T> page, EntityWrapper<T> entityWrapper) {
  if (null != entityWrapper) {
      entityWrapper.orderBy(page.getOrderByField(), page.isAsc());
  }
  page.setRecords(baseMapper.selectPage(page, entityWrapper));
  return page;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 拼接 sql 方式 一
@Test
public void testTSQL11() {
    /*
     * 實體帶查詢使用方法  輸出看結果
     */
    EntityWrapper<User> ew = new EntityWrapper<User>();
    ew.setEntity(new User(1));
    ew.where("user_name={0}", "'zhangsan'").and("id=1")
            .orNew("user_status={0}", "0").or("status=1")
            .notLike("user_nickname", "notvalue")
            .andNew("new=xx").like("hhh", "ddd")
            .andNew("pwd=11").isNotNull("n1,n2").isNull("n3")
            .groupBy("x1").groupBy("x2,x3")
            .having("x1=11").having("x3=433")
            .orderBy("dd").orderBy("d1,d2");
    System.out.println(ew.getSqlSegment());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 拼接 sql 方式 二
int buyCount = selectCount(Condition.create()
                .setSqlSelect("sum(quantity)")
                .isNull("order_id")
                .eq("user_id", 1)
                .eq("type", 1)
                .in("status", new Integer[]{0, 1})
                .eq("product_id", 1)
                .between("created_time", startDate, currentDate)
                .eq("weal", 1));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 自定義 SQL 方法如何使用 Wrapper

mapper java 接口方法

List selectMyPage(RowBounds rowBounds, @Param(“ew”) Wrapper wrapper);

mapper xml 定義

<select id="selectMyPage" resultType="User">
  SELECT * FROM user 
  <where>
  ${ew.sqlSegment}
  </where>
</select>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

插件擴展

分頁插件
  • 自定義查詢語句分頁(自己寫sql/mapper)
  • spring 注入 mybatis 配置分頁插件
<plugins>
    <!--
     | 分頁插件配置
     | 插件提供二種方言選擇:1、默認方言 2、自定義方言實現類,兩者均未配置則拋出異常!
     | overflowCurrent 溢出總頁數,設置第一頁 默認false
     | optimizeType Count優化方式 ( 版本 2.0.9 改爲使用 jsqlparser 不需要配置 )
     | -->
    <!-- 注意!! 如果要支持二級緩存分頁使用類 CachePaginationInterceptor 默認、建議如下!! -->
    <plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
        <property name="sqlParser" ref="自定義解析類、可以沒有" />
        <property name="localPage" value="默認 false 改爲 true 開啓了 pageHeper 支持、可以沒有" />
        <property name="dialectClazz" value="自定義方言類、可以沒有" />
    </plugin>
</plugins>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {

    /**
     * 分頁插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
方式一 、傳參區分模式【推薦】
  • UserMapper.java 方法內容
public interface UserMapper{//可以繼承或者不繼承BaseMapper
    /**
     * <p>
     * 查詢 : 根據state狀態查詢用戶列表,分頁顯示
     * </p>
     *
     * @param page
     *            翻頁對象,可以作爲 xml 參數直接使用,傳遞參數 Page 即自動分頁
     * @param state
     *            狀態
     * @return
     */
    List<User> selectUserList(Pagination page, Integer state);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • UserServiceImpl.java 調用翻頁方法,需要 page.setRecords 回傳給頁面
public Page<User> selectUserPage(Page<User> page, Integer state) {
    page.setRecords(userMapper.selectUserList(page, state));
    return page;
}
  • 1
  • 2
  • 3
  • 4
  • UserMapper.xml 等同於編寫一個普通 list 查詢,mybatis-plus 自動替你分頁
<select id="selectUserList" resultType="User">
    SELECT * FROM user WHERE state=#{state}
</select>
  • 1
  • 2
  • 3
方式二、ThreadLocal 模式【容易出錯,不推薦】
  • PageHelper 使用方式如下:
// 開啓分頁
PageHelper.startPage(1, 2);
List<User> data = userService.findAll(params);
// 獲取總條數
int total = PageHelper.getTotal();
// 獲取總條數,並釋放資源
int total = PageHelper.freeTotal();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
執行分析插件

SQL 執行分析攔截器【 目前只支持 MYSQL-5.6.3 以上版本 】,作用是分析 處理 DELETE UPDATE 語句, 防止小白或者惡意 delete update 全表操作!

<plugins>
    <!-- SQL 執行分析攔截器 stopProceed 發現全表執行 delete update 是否停止運行 -->
    <plugin interceptor="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor">
        <property name="stopProceed" value="false" />
    </plugin>
</plugins>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

注意!參數說明

  • 參數:stopProceed 發現執行全表 delete update 語句是否停止執行
  • 注意!該插件只用於開發環境,不建議生產環境使用。。。
性能分析插件

性能分析攔截器,用於輸出每條 SQL 語句及其執行時間

  • 使用如下:
<plugins>
    ....

    <!-- SQL 執行性能分析,開發環境使用,線上不推薦。 maxTime 指的是 sql 最大執行時長 -->
    <plugin interceptor="com.baomidou.mybatisplus.plugins.PerformanceInterceptor">
        <property name="maxTime" value="100" />
        <!--SQL是否格式化 默認false-->
        <property name="format" value="true" />
    </plugin>
</plugins>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {

    /**
     * SQL執行效率插件
     */
    @Bean
    @Profile({"dev","test"})// 設置 dev test 環境開啓
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注意!參數說明

  • 參數:maxTime SQL 執行最大時長,超過自動停止運行,有助於發現問題。
  • 參數:format SQL SQL是否格式化,默認false。
樂觀鎖插件

主要使用場景:

意圖:

當要更新一條記錄的時候,希望這條記錄沒有被別人更新

樂觀鎖實現方式:

  • 取出記錄時,獲取當前version
  • 更新時,帶上這個version
  • 執行更新時, set version = yourVersion+1 where version = yourVersion
  • 如果version不對,就更新失敗
插件配置
<bean class="com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor"/>
  • 1
註解實體字段 @Version 必須要!
public class User {

    @Version
    private Integer version;

    ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

特別說明: **僅支持int,Integer,long,Long,Date,Timestamp

示例Java代碼

int id = 100;
int version = 2;

User u = new User();
u.setId(id);
u.setVersion(version);
u.setXXX(xxx);

if(userService.updateById(u)){
    System.out.println("Update successfully");
}else{
    System.out.println("Update failed due to modified by others");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

示例SQL原理

update tbl_user set name='update',version=3 where id=100 and version=2;
  • 1
XML文件熱加載

開啓動態加載 mapper.xml

  • 多數據源配置多個 MybatisMapperRefresh 啓動 bean
參數說明:
      sqlSessionFactory:session工廠
      mapperLocations:mapper匹配路徑
      enabled:是否開啓動態加載  默認:false
      delaySeconds:項目啓動延遲加載時間  單位:秒  默認:10s
      sleepSeconds:刷新時間間隔  單位:秒 默認:20s
  提供了兩個構造,挑選一個配置進入spring配置文件即可:

構造1:
    <bean class="com.baomidou.mybatisplus.spring.MybatisMapperRefresh">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="mapperLocations" value="classpath*:mybatis/mappers/*/*.xml"/>
        <constructor-arg name="enabled" value="true"/>
    </bean>

構造2:
    <bean class="com.baomidou.mybatisplus.spring.MybatisMapperRefresh">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="mapperLocations" value="classpath*:mybatis/mappers/*/*.xml"/>
        <constructor-arg name="delaySeconds" value="10"/>
        <constructor-arg name="sleepSeconds" value="20"/>
        <constructor-arg name="enabled" value="true"/>
    </bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
自定義全局操作

自定義注入全表刪除方法 deteleAll 
自定義 MySqlInjector 注入類 java 代碼如下:

public class MySqlInjector extends AutoSqlInjector {

    @Override
    public void inject(Configuration configuration, MapperBuilderAssistant builderAssistant, Class<?> mapperClass,
            Class<?> modelClass, TableInfo table) {
        /* 添加一個自定義方法 */
        deleteAllUser(mapperClass, modelClass, table);
    }

    public void deleteAllUser(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {

        /* 執行 SQL ,動態 SQL 參考類 SqlMethod */
        String sql = "delete from " + table.getTableName();

        /* mapper 接口方法名一致 */
        String method = "deleteAll";
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        this.addMappedStatement(mapperClass, method, sqlSource, SqlCommandType.DELETE, Integer.class);
    }

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

當然你的 mapper.java 接口類需要申明使用方法 deleteAll 如下

public interface UserMapper extends BaseMapper<User> {

    /**
     * 自定義注入方法
     */
    int deleteAll();

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

最後一步注入啓動

<!-- 定義 MP 全局策略,安裝集成文檔部分結合 -->
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
    .....

  <!-- 自定義注入 deleteAll 方法  -->
  <property name="sqlInjector" ref="mySqlInjector" />
</bean>

<!-- 自定義注入器 -->
<bean id="mySqlInjector" class="com.baomidou.test.MySqlInjector" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 完成如上幾步共享,注入完成!可以開始使用了。。。
公共字段自動填充
  • 實現元對象處理器接口: com.baomidou.mybatisplus.mapper.IMetaObjectHandler
  • 註解填充字段 @TableField(.. fill = FieldFill.INSERT) 生成器策略部分也可以配置!
public class User {

    // 注意!這裏需要標記爲填充字段
    @TableField(.. fill = FieldFill.INSERT)
    private String fillField;

    ....
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 自定義實現類 MyMetaObjectHandler
/**  自定義填充公共 name 字段  */
public class MyMetaObjectHandler extends MetaObjectHandler {

    /**
     * 測試 user 表 name 字段爲空自動填充
     */
    public void insertFill(MetaObject metaObject) {
        // 更多查看源碼測試用例
        System.out.println("*************************");
        System.out.println("insert fill");
        System.out.println("*************************");

        // 測試下劃線
        Object testType = getFieldValByName("testType", metaObject);//mybatis-plus版本2.0.9+
        System.out.println("testType=" + testType);
        if (testType == null) {
            setFieldValByName("testType", 3, metaObject);//mybatis-plus版本2.0.9+
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //更新填充
        System.out.println("*************************");
        System.out.println("update fill");
        System.out.println("*************************");
        //mybatis-plus版本2.0.9+
        setFieldValByName("lastUpdatedDt", new Timestamp(System.currentTimeMillis()), metaObject);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

spring 啓動注入 MyMetaObjectHandler 配置

<!-- MyBatis SqlSessionFactoryBean 配置 -->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
    <property name="globalConfig" ref="globalConfig"></property>
</bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
    <!-- 公共字段填充處理器 -->
    <property name="metaObjectHandler" ref="myMetaObjectHandler" />
</bean>
<!-- 自定義處理器 -->
<bean id="myMetaObjectHandler" class="com.baomidou.test.MyMetaObjectHandler" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
邏輯刪除
開啓配置

1、修改 集成 全局注入器爲 LogicSqlInjector 
2、全局注入值: 
logicDeleteValue // 邏輯刪除全局值 
logicNotDeleteValue // 邏輯未刪除全局值

3、邏輯刪除的字段需要註解 @TableLogic

Mybatis-Plus邏輯刪除視頻教程

全局配置注入LogicSqlInjector Java Config方式:

@Bean
public GlobalConfiguration globalConfiguration() {
    GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
    conf.setLogicDeleteValue("-1");
    conf.setLogicNotDeleteValue("1");
    conf.setIdType(2);
    return conf;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

XML配置方式:

<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
    <property name="sqlInjector" ref="logicSqlInjector" />
    <property name="logicDeleteValue" value="-1" />
    <property name="logicNotDeleteValue" value="1" />
    <property name="idType" value="2" />
</bean>

<bean id="logicSqlInjector" class="com.baomidou.mybatisplus.mapper.LogicSqlInjector" />
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

邏輯刪除實體

@TableName("tbl_user")
public class UserLogicDelete {

    private Long id;
    ...

    @TableField(value = "delete_flag")
    @TableLogic
    private Integer deleteFlag;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
邏輯刪除效果

會在mp自帶查詢和更新方法的sql後面,追加『邏輯刪除字段』=『LogicNotDeleteValue默認值』 刪除方法: deleteById()和其他delete方法, 底層SQL調用的是update tbl_xxx set 『邏輯刪除字段』=『logicDeleteValue默認值』

多數據源

第一步:擴展Spring的AbstractRoutingDataSource抽象類,實現動態數據源。 AbstractRoutingDataSource中的抽象方法determineCurrentLookupKey是實現數據源的route的核心,這裏對該方法進行Override。 【上下文DbContextHolder爲一線程安全的ThreadLocal】具體代碼如下:

public class DynamicDataSource extends AbstractRoutingDataSource {

/**
 * 取得當前使用哪個數據源
 * @return
 */
@Override
protected Object determineCurrentLookupKey() {
    return DbContextHolder.getDbType();
}
}

public class DbContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal<>();

/**
 * 設置數據源
 * @param dbTypeEnum
 */
public static void setDbType(DBTypeEnum dbTypeEnum) {
    contextHolder.set(dbTypeEnum.getValue());
}

/**
 * 取得當前數據源
 * @return
 */
public static String getDbType() {
    return contextHolder.get();
}

/**
 * 清除上下文數據
 */
public static void clearDbType() {
    contextHolder.remove();
}
}

public enum DBTypeEnum {
one("dataSource_one"), two("dataSource_two");
private String value;

DBTypeEnum(String value) {
    this.value = value;
}

public String getValue() {
    return value;
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

第二步:配置動態數據源將DynamicDataSource Bean加入到Spring的上下文xml配置文件中去,同時配置DynamicDataSource的targetDataSources(多數據源目標)屬性的Map映射。 代碼如下【我省略了dataSource_one和dataSource_two的配置】:

<bean id="dataSource" class="com.miyzh.dataclone.db.DynamicDataSource">
    <property name="targetDataSources">
        <map key-type="java.lang.String">
            <entry key="dataSource_one" value-ref="dataSource_one" />
            <entry key="dataSource_two" value-ref="dataSource_two" />
        </map>
    </property>
    <property name="defaultTargetDataSource" ref="dataSource_two" />
</bean>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

第三步:使用動態數據源:DynamicDataSource是繼承與AbstractRoutingDataSource,而AbstractRoutingDataSource又是繼承於org.springframework.jdbc.datasource.AbstractDataSource,AbstractDataSource實現了統一的DataSource接口,所以DynamicDataSource同樣可以當一個DataSource使用。

@Test 
public void test() {
DbContextHolder.setDbType(DBTypeEnum.one);
List userList = iUserService.selectList(new EntityWrapper());
for (User user : userList) {
log.debug(user.getId() + "#" + user.getName() + "#" + user.getAge());
}

    DbContextHolder.setDbType(DBTypeEnum.two);
    List<IdsUser> idsUserList = iIdsUserService.selectList(new EntityWrapper<IdsUser>());
    for (IdsUser idsUser : idsUserList) {
        log.debug(idsUser.getMobile() + "#" + idsUser.getUserName());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

說明:

  • 1、事務管理:使用動態數據源的時候,可以看出和使用單數據源的時候相比,在使用配置上幾乎沒有差別,在進行性事務管理配置的時候也沒有差別:
  • 2、通過擴展Spring的AbstractRoutingDataSource可以很好的實現多數據源的rout效果,而且對擴展更多的數據源有良好的伸縮性,只要增加數據源和修改DynamicDataSource的targetDataSources屬性配置就好。在數據源選擇控制上,可以採用手動控制(業務邏輯並不多的時候),也可以很好的用AOP的@Aspect在Service的入口加入一個切面@Pointcut,在@Before裏判斷JoinPoint的類容選定特定的數據源。
Sequence主鍵

實體主鍵支持Sequence @since 2.0.8

  • oracle主鍵策略配置Sequence
  • GlobalConfiguration配置KeyGenerator
GlobalConfiguration gc = new GlobalConfiguration();
  //gc.setDbType("oracle");//不需要這麼配置了
  gc.setKeyGenerator(new OracleKeyGenerator());
  • 1
  • 2
  • 3
  • 實體類配置主鍵Sequence,指定主鍵@TableId(type=IdType.INPUT)//不能使用AUTO
@TableName("TEST_SEQUSER")
@KeySequence("SEQ_TEST")//類註解
public class TestSequser{
  @TableId(value = "ID", type = IdType.INPUT)
  private Long id;

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 支持父類定義@KeySequence, 子類使用
@KeySequence("SEQ_TEST")
public abstract class Parent{

}
public class Child extends Parent{

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

以上步驟就可以使用Sequence當主鍵了。

多租戶 SQL 解析器
  • 這裏配合 分頁攔截器 使用, spring boot 例子配置如下:
@Bean
public PaginationInterceptor paginationInterceptor() {
    PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
    paginationInterceptor.setLocalPage(true);// 開啓 PageHelper 的支持
    /*
     * 【測試多租戶】 SQL 解析處理攔截器<br>
     * 這裏固定寫成住戶 1 實際情況你可以從cookie讀取,因此數據看不到 【 麻花藤 】 這條記錄( 注意觀察 SQL )<br>
     */
    List<ISqlParser> sqlParserList = new ArrayList<>();
    TenantSqlParser tenantSqlParser = new TenantSqlParser();
    tenantSqlParser.setTenantHandler(new TenantHandler() {
        @Override
        public Expression getTenantId() {
            return new LongValue(1L);
        }

        @Override
        public String getTenantIdColumn() {
            return "tenant_id";
        }

        @Override
        public boolean doTableFilter(String tableName) {
            // 這裏可以判斷是否過濾表
            /*
            if ("user".equals(tableName)) {
                return true;
            }*/
            return false;
        }
    });
    sqlParserList.add(tenantSqlParser);
    paginationInterceptor.setSqlParserList(sqlParserList);
    paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
        @Override
        public boolean doFilter(MetaObject metaObject) {
            MappedStatement ms = PluginUtils.getMappedStatement(metaObject);
            // 過濾自定義查詢此時無租戶信息約束【 麻花藤 】出現
            if ("com.baomidou.springboot.mapper.UserMapper.selectListBySQL".equals(ms.getId())) {
                return true;
            }
            return false;
        }
    });
    return paginationInterceptor;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
通用枚舉掃描並自動關聯注入
1、自定義枚舉實現 IEnum 接口,申明自動注入爲通用枚舉轉換處理器

枚舉屬性,必須實現 IEnum 接口如下:

public enum AgeEnum implements IEnum {
    ONE(1, "一歲"),
    TWO(2, "二歲");

    private int value;
    private String desc;

    AgeEnum(final int value, final String desc) {
        this.value = value;
        this.desc = desc;
    }

    @Override
    public Serializable getValue() {
        return this.value;
    }

    @JsonValue // Jackson 註解,可序列化該屬性爲中文描述【可無】
    public String getDesc(){
        return this.desc;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
2、配置掃描通用枚舉
  • 注意!! spring mvc 配置參考,安裝集成 MybatisSqlSessionFactoryBean 枚舉包掃描,spring boot 例子配置如下:

配置文件 resources/application.yml

mybatis-plus:
    # 支持統配符 * 或者 ; 分割
    typeEnumsPackage: com.baomidou.springboot.entity.enums
  ....
  • 1
  • 2
  • 3
  • 4
MybatisX idea 快速開發插件

MybatisX 輔助 idea 快速開發插件,爲效率而生。【入 Q 羣 576493122 附件下載! 或者 官方搜索 mybatisx 安裝】

  • 官方安裝: File -> Settings -> Plugins -> Browse Repositories.. 輸入 mybatisx 安裝下載
  • Jar 安裝: File -> Settings -> Plugins -> Install plugin from disk.. 選中 mybatisx..jar 安裝
功能
  • java xml 調回跳轉,mapper 方法自動生成 xml
計劃支持
  • 連接數據源之後xml裏自動提示字段
  • sql 增刪改查
  • 集成 MP 代碼生成
  • 其他
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章