溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用MybatisPlus自定義模版中能獲取到的信息

發(fā)布時間:2022-05-23 09:40:15 來源:億速云 閱讀:161 作者:zzz 欄目:開發(fā)技術(shù)

這篇文章主要介紹“如何使用MybatisPlus自定義模版中能獲取到的信息”的相關(guān)知識,小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“如何使用MybatisPlus自定義模版中能獲取到的信息”文章能幫助大家解決問題。

使用MybatisPlus的AutoGenerator生成代碼

這個可自行官網(wǎng)查看,或者搜索引擎查一下一大堆可以參考的,這里就不過多敘述。

模版中能獲取到哪些信息

官方?jīng)]有給出在自定義模版中你能獲取到哪些信息來生成你想要的代碼,所以本人就看了一下源碼,能獲取到的信息都在com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine類的getObjectMap方法中,如下:

    /**
     * <p>
     * 渲染對象 MAP 信息
     * </p>
     *
     * @param tableInfo 表信息對象
     * @return
     */
    public Map<String, Object> getObjectMap(TableInfo tableInfo) {
        Map<String, Object> objectMap = new HashMap<>();
        ConfigBuilder config = this.getConfigBuilder();
        if (config.getStrategyConfig().isControllerMappingHyphenStyle()) {
            objectMap.put("controllerMappingHyphenStyle", config.getStrategyConfig().isControllerMappingHyphenStyle());
            objectMap.put("controllerMappingHyphen", StringUtils.camelToHyphen(tableInfo.getEntityPath()));
        }
        objectMap.put("restControllerStyle", config.getStrategyConfig().isRestControllerStyle());
        objectMap.put("package", config.getPackageInfo());
        GlobalConfig globalConfig = config.getGlobalConfig();
        objectMap.put("author", globalConfig.getAuthor());
        objectMap.put("idType", globalConfig.getIdType() == null ? null : globalConfig.getIdType().toString());
        objectMap.put("logicDeleteFieldName", config.getStrategyConfig().getLogicDeleteFieldName());
        objectMap.put("versionFieldName", config.getStrategyConfig().getVersionFieldName());
        objectMap.put("activeRecord", globalConfig.isActiveRecord());
        objectMap.put("kotlin", globalConfig.isKotlin());
        objectMap.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        objectMap.put("table", tableInfo);
        objectMap.put("enableCache", globalConfig.isEnableCache());
        objectMap.put("baseResultMap", globalConfig.isBaseResultMap());
        objectMap.put("baseColumnList", globalConfig.isBaseColumnList());
        objectMap.put("entity", tableInfo.getEntityName());
        objectMap.put("entityColumnConstant", config.getStrategyConfig().isEntityColumnConstant());
        objectMap.put("entityBuilderModel", config.getStrategyConfig().isEntityBuilderModel());
        objectMap.put("entityLombokModel", config.getStrategyConfig().isEntityLombokModel());
        objectMap.put("entityBooleanColumnRemoveIsPrefix", config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix());
        objectMap.put("superEntityClass", this.getSuperClassName(config.getSuperEntityClass()));
        objectMap.put("superMapperClassPackage", config.getSuperMapperClass());
        objectMap.put("superMapperClass", this.getSuperClassName(config.getSuperMapperClass()));
        objectMap.put("superServiceClassPackage", config.getSuperServiceClass());
        objectMap.put("superServiceClass", this.getSuperClassName(config.getSuperServiceClass()));
        objectMap.put("superServiceImplClassPackage", config.getSuperServiceImplClass());
        objectMap.put("superServiceImplClass", this.getSuperClassName(config.getSuperServiceImplClass()));
        objectMap.put("superControllerClassPackage", config.getSuperControllerClass());
        objectMap.put("superControllerClass", this.getSuperClassName(config.getSuperControllerClass()));
        return objectMap;
    }

下面我就順便整理一下方便以后查看

屬性類型描述示例
controllerMappingHyphenStylebooleancontrollerMapping是否為連字符形式駝峰:@RequestMapping("/managerUserActionHistory")連字符:@RequestMapping("/manager-user-action-history")
controllerMappingHyphenString實(shí)體類的連字符形式manager-user-action-history
restControllerStyleboolean是否為RestController模式 
packageMap所有包配置信息 
package.EntityStringEntity所在包路徑com.geek.sean.test.model
package.MapperStringMapper所在包路徑com.geek.sean.test.mapper
package.XmlStringMapper的xml文件所在包路徑com.geek.sean.test.mapper.xml
package.ServiceImplStringService實(shí)現(xiàn)類所在包路徑com.geek.sean.test.service.impl
package.ServiceStringService所在包路徑com.geek.sean.test.service
package.ControllerStringController所在包路徑com.geek.sean.test.controller
authorStringGlobalConfig中配置的author 
idTypeStringGlobalConfig中配置的idType 
logicDeleteFieldNameString策略配置項(xiàng)中配置的邏輯刪除屬性名稱 
versionFieldNameString策略配置項(xiàng)中配置的樂觀鎖屬性名稱 
activeRecordboolean是否開啟ActiveRecord模式 
kotlinboolean是否開啟 Kotlin 模式 
dateString當(dāng)前日期(yyyy-MM-dd)2019-07-09
tableTableInfo表信息,關(guān)聯(lián)到當(dāng)前字段信息 
table.nameString表名例:sys_user
table.commentString表描述用戶信息表
table.entityNameString實(shí)體類名稱SysUser
table.mapperNameStringMapper類名SysUserMapper
table.xmlNameStringMapper對應(yīng)的xml名稱SysUserMapper
table.serviceNameStringService名稱SysUserService
table.serviceImplNameStringService實(shí)現(xiàn)類名稱SysUserServiceImpl
table.controllerNameStringController名稱SysUserController
table.fieldsList<TableField>字段信息集合 
table.fields[n].nameString字段名稱user_id
table.fields[n].typeString字段類型int(11)、varchar(64)、timestamp、char(1)
table.fields[n].propertyNameString屬性名userId、userName
table.fields[n].columnTypeString屬性類型String、Integer
table.fields[n].commentString字段描述用戶名
table.importPackagesList<String>引入包集合[&lsquo;com.baomidou.mybatisplus.enums.IdType&rsquo;,&lsquo;java.util.Date&rsquo;]
table.fieldNamesString表字段名,逗號分隔user_id, user_name, password
enableCacheboolean是否在xml中添加二級緩存配置 
baseResultMapboolean是否開啟 BaseResultMap 
baseColumnListboolean是否開啟 baseColumnList 
entityStringEntity類名 
entityColumnConstantboolean【實(shí)體】是否生成字段常量(默認(rèn) false) 
entityBuilderModelboolean【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false) 
entityLombokModelboolean【實(shí)體】是否為lombok模型(默認(rèn) false) 
entityBooleanColumnRemoveIsPrefixbooleanBoolean類型字段是否移除is前綴(默認(rèn) false)比如 : 數(shù)據(jù)庫字段名稱 : &lsquo;is_xxx&rsquo;,類型為 : tinyint. 在映射實(shí)體的時候則會去掉is,在實(shí)體類中映射最終結(jié)果為 xxx
superEntityClassStringEntity父類BaseEntity
superMapperClassPackageStringMapper父類包路徑com.baomidou.mybatisplus.mapper.BaseMapper
superMapperClassStringMapper父類BaseMapper
superServiceClassPackageStringService父類包路徑com.baomidou.mybatisplus.service.IService
superServiceClassStringService父類IService
superServiceImplClassPackageStringService實(shí)現(xiàn)類父類包路徑com.baomidou.mybatisplus.service.impl.ServiceImpl
superServiceImplClassStringService實(shí)現(xiàn)類父類ServiceImpl
superControllerClassPackageStringController類父類包路徑 
superControllerClassStringController父類 

總結(jié)了一上午,個別字段沒有放上,自己用到時候可以再去源碼看看。

MybatisPlus遇到的坑

springBoot項(xiàng)目整合mybatis-plus、lombok時遇到了使用代碼生成器生成實(shí)體類及mapper后,調(diào)用方法時報(bào)錯找不到mapper,后經(jīng)過一項(xiàng)項(xiàng)調(diào)整pom文件內(nèi)jar包依賴,才知道m(xù)ybatis-plus版本號存在很多不兼容。

1、導(dǎo)入依賴

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- mybatis的orm插件 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>2.1.9</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatisplus-spring-boot-starter</artifactId>
            <version>1.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <!--阿里數(shù)據(jù)庫鏈接依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

因?yàn)槲矣玫氖前⒗镌频臄?shù)據(jù)庫,所以需要導(dǎo)入阿里云及數(shù)據(jù)庫依賴,lombok為簡化實(shí)體類生成的插件jar包。

注意:千萬注意mybatis-plus版本?。?!千萬注意mybatis-plus版本?。。∏f注意mybatis-plus版本?。?!

2、配置分頁配置文件和數(shù)據(jù)源

package com.ds.tech.config;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.alibaba.druid.pool.DruidDataSource;
/**
 * 數(shù)據(jù)源配置
 */
@Configuration
public class DataSourceConfig {
 
    @Bean(name="dataSource")
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource dataSource(){
        return new DruidDataSource();
    }
 
    // 配置事物管理器
    @Bean(name="transactionManager")
    public DataSourceTransactionManager transactionManager(){
        return new DataSourceTransactionManager(dataSource());
    }
}
package com.ds.tech.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
@Configuration
//掃描dao或者是Mapper接口
@MapperScan("com.ds.tech.mapper*")
public class MybatisPlusConfig {
  /**
   * mybatis-plus 分頁插件
   */
  @Bean
  public PaginationInterceptor paginationInterceptor(){
      PaginationInterceptor page = new PaginationInterceptor();
      page.setDialectType("mysql");
      return page;
  }
}

配置代碼生成器,然后就可以生成代碼使用了 

package com.ds.tech;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
/**
 * <p>
 * 代碼生成器演示
 * </p>
 */
public class MpGenerator { 
    final static String  dirPath = "D://mybatis";
 
    /**
     * <p>
     * MySQL 生成演示
     * </p>
     */
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();
        // 選擇 freemarker 引擎,默認(rèn) Veloctiy
        //mpg.setTemplateEngine(new FreemarkerTemplateEngine());
 
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(dirPath);
        gc.setAuthor("dashen");
        gc.setFileOverride(true); //是否覆蓋
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的請改為false
        gc.setEnableCache(false);// XML 二級緩存
        gc.setBaseResultMap(false);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList
 
        // 自定義文件命名,注意 %s 會自動填充表實(shí)體屬性!
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sMapper");
        // gc.setServiceName("MP%sService");
        // gc.setServiceImplName("%sServiceDiy");
        // gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);
 
        // 數(shù)據(jù)源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert(){
            // 自定義數(shù)據(jù)庫表字段類型轉(zhuǎn)換【可選】
//            @Override
//            public DbColumnType processTypeConvert(String fieldType) {
//                System.out.println("轉(zhuǎn)換類型:" + fieldType);
//                // 注意??!processTypeConvert 存在默認(rèn)類型轉(zhuǎn)換,如果不是你要的效果請自定義返回、非如下直接返回。
//                return super.processTypeConvert(fieldType);
//            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("k");
        dsc.setPassword("mj^");
        dsc.setUrl("jdbc:mysql://rm-2zql.rds.aliyuncs.06/mjmk_dev?useUnicode=true&characterEncoding=utf-8");
        mpg.setDataSource(dsc);
 
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // strategy.setCapitalMode(true);// 全局大寫命名 ORACLE 注意
        strategy.setTablePrefix(new String[] { "tb_", "tsys_" });// 此處可以修改為您的表前綴
        strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
        strategy.setInclude(new String[] { "store" }); // 需要生成的表
        // strategy.setExclude(new String[]{"test"}); // 排除生成的表
        // 自定義實(shí)體父類
        // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
        // strategy.setSuperEntityClass("java.io.Serializable");
        // 自定義實(shí)體,公共字段
        // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
        // 自定義 mapper 父類
        // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        // 自定義 service 父類
        // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        // 自定義 service 實(shí)現(xiàn)類父類
        // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
        // 自定義 controller 父類
        // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
        // 【實(shí)體】是否生成字段常量(默認(rèn) false)
        // public static final String ID = "test_id";
        // strategy.setEntityColumnConstant(true);
        // 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false)
        // public User setName(String name) {this.name = name; return this;}
         strategy.setEntityBuilderModel(true);
         strategy.setEntityLombokModel(true);
        mpg.setStrategy(strategy);
 
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.ds.tech");
//        pc.setModuleName("");
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setServiceImpl("serviceImpl");
        pc.setXml("mapperXml");
 
        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);*/
 
        // 調(diào)整 xml 生成目錄演示
/*        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return dirPath + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        cfg.setFileOutConfigList(focList);
        */
        mpg.setCfg(cfg);
 
        // 關(guān)閉默認(rèn) xml 生成,調(diào)整生成 至 根目錄
/*        TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);*/
 
        // 自定義模板配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面內(nèi)容修改,
        // 放置自己項(xiàng)目的 src/main/resources/templates 目錄下, 默認(rèn)名稱一下可以不配置,也可以自定義模板名稱
        // TemplateConfig tc = new TemplateConfig();
        // tc.setController("...");
        // tc.setEntity("...");
        // tc.setMapper("...");
        // tc.setXml("...");
        // tc.setService("...");
        // tc.setServiceImpl("...");
        // 如上任何一個模塊如果設(shè)置 空 OR Null 將不生成該模塊。
        // mpg.setTemplate(tc);
 
        // 執(zhí)行生成
        mpg.execute();
 
        // 打印注入設(shè)置【可無】
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }
}

關(guān)于“如何使用MybatisPlus自定義模版中能獲取到的信息”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI