Mybatis-plus?代碼生成器?AutoGenerator?的簡介和使用詳解
前言
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個模塊的代碼,極大的提升了開發(fā)效率。
使用MyBatis-Plus只是我覺得它很方便,但真到了實際項目中,邏輯復雜的項目,就要斟酌一下了。
一、添加依賴
MyBatis-Plus 從 3.0.3 之后移除了代碼生成器與模板引擎的默認依賴,需要手動添加相關(guān)依賴。以下是AutoGenerator代碼生成器和freemarker模板引擎依賴(模板引擎選一種,也可以自定義模板引擎):
<!--mybatis-plus(springboot版)--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <!--mybatis-plus代碼生成器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.0</version> </dependency> <!--Velocity(默認)模板引擎--> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency> <!--freemarker模板引擎(博主用的)--> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.30</version> </dependency> <!--beetl模板引擎--> <dependency> <groupId>com.ibeetl</groupId> <artifactId>beetl</artifactId> <version>3.2.1.RELEASE</version> </dependency>
自定義模板引擎例子
// AutoGenerator代碼生成器 AutoGenerator generator = new AutoGenerator(); // freemarker engine generator.setTemplateEngine(new FreemarkerTemplateEngine()); // beetl engine generator.setTemplateEngine(new BeetlTemplateEngine()); // custom engine generator.setTemplateEngine(new CustomTemplateEngine()); generator.setTemplateEngine(自定義模板引擎);
二、自定義參數(shù)
MyBatis-Plus 的代碼生成器提供了大量的自定義參數(shù)供用戶選擇,能夠滿足絕大部分人的使用需求。以下兩個鏈接分別為官方鏈接和博主自定義的參數(shù)鏈接(我寫的注釋全些)。
1、配置 GlobalConfig(全局配置)
// 全局配置 GlobalConfig gc = new GlobalConfig(); //項目根目錄 String projectPath = System.getProperty("user.dir"); //用于多個模塊下生成到精確的目錄下(我設(shè)置在桌面) //String projectPath = "C:/Users/xie/Desktop"; //代碼生成目錄 gc.setOutputDir(projectPath + "/src/main/java"); //開發(fā)人員 gc.setAuthor("先謝郭嘉"); // 是否打開輸出目錄(默認值:null) gc.setOpen(false); //實體屬性 Swagger2 注解 gc.setSwagger2(true); //去掉接口上的I //gc.setServiceName("%Service"); // 配置時間類型策略(date類型),如果不配置會生成LocalDate類型 gc.setDateType(DateType.ONLY_DATE); // 是否覆蓋已有文件(默認值:false) gc.setFileOverride(true); //把全局配置添加到代碼生成器主類 mpg.setGlobalConfig(gc);
2、 配置 DataSourceConfig(數(shù)據(jù)源配置)
// 數(shù)據(jù)源配置 DataSourceConfig dsc = new DataSourceConfig(); //數(shù)據(jù)庫連接 dsc.setUrl("jdbc:mysql://localhost:3306/blog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8"); // 數(shù)據(jù)庫 schema name //dsc.setSchemaName("public"); // 數(shù)據(jù)庫類型 dsc.setDbType(DbType.MYSQL); // 驅(qū)動名稱 dsc.setDriverName("com.mysql.cj.jdbc.Driver"); //用戶名 dsc.setUsername("root"); //密碼 dsc.setPassword("430423"); //把數(shù)據(jù)源配置添加到代碼生成器主類 mpg.setDataSource(dsc);
3、 配置PackageConfig(包名配置)
// 包配置 PackageConfig pc = new PackageConfig(); // 添加這個后 會以一個實體為一個模塊 比如user實體會生成user模塊 每個模塊下都會生成三層 // pc.setModuleName(scanner("模塊名")); // 父包名。如果為空,將下面子包名必須寫全部, 否則就只需寫子包名 pc.setParent("com.xxgg.blog"); // Service包名 pc.setService("service"); // Entity包名 pc.setEntity("entity"); // ServiceImpl包名 pc.setServiceImpl("service.impl"); // Mapper包名 pc.setMapper("mapper"); // Controller包名 pc.setController("controller"); // Mapper.xml包名 pc.setXml("mapper"); // 把包配置添加到代碼生成器主類 mpg.setPackageInfo(pc);
4、 配置InjectionConfig(自定義配置)
// 自定義配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定義輸出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定義配置會被優(yōu)先輸出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱會跟著發(fā)生變化!! return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判斷自定義文件夾是否需要創(chuàng)建 checkDir("調(diào)用默認方法創(chuàng)建的目錄,自定義目錄用"); if (fileType == FileType.MAPPER) { // 已經(jīng)生成 mapper 文件判斷存在,不想重新生成返回 false return !new File(filePath).exists(); } // 允許生成模板文件 return true; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);
5、 配置TemplateConfig(模板配置)
// 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定義輸出模板 //指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據(jù)使用的模板引擎自動識別 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig);
6、配置StrategyConfig(策略配置)
// 策略配置,我喜歡叫數(shù)據(jù)庫表配置 StrategyConfig strategy = new StrategyConfig(); // 數(shù)據(jù)庫表映射到實體的命名策略:下劃線轉(zhuǎn)駝峰 strategy.setNaming(NamingStrategy.underline_to_camel); // 數(shù)據(jù)庫表字段映射到實體的命名策略, 未指定按照 naming 執(zhí)行 strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 實體是否為lombok模型(默認 false) strategy.setEntityLombokModel(true); // 生成 @RestController 控制器 strategy.setRestControllerStyle(true); // 實體類主鍵名稱設(shè)置 strategy.setSuperEntityColumns("id"); // 需要包含的表名,允許正則表達式 //這里我做了輸入設(shè)置 strategy.setInclude(scanner("表名,多個英文逗號分割").split(",")); // 需要排除的表名,允許正則表達式 //strategy.setExclude("***"); // 是否生成實體時,生成字段注解 默認false; strategy.setEntityTableFieldAnnotationEnable(true); // 駝峰轉(zhuǎn)連字符 strategy.setControllerMappingHyphenStyle(true); // 表前綴 strategy.setTablePrefix(pc.getModuleName() + "_"); // 把數(shù)據(jù)庫配置添加到代碼生成器主類 mpg.setStrategy(strategy);
7、生成
// 在代碼生成器主類上配置模板引擎 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); //生成 mpg.execute();
三、演示
1、代碼
/** * @description: 代碼生成器 * @author: 先謝郭嘉 * @create: 2020-09-29 09:04 **/ public class CodeGenerator { /** * <p> * 讀取控制臺內(nèi)容 * </p> */ public static String scanner(String tip) { //獲取控制臺輸入值 Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("請輸入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { return ipt; } } throw new MybatisPlusException("請輸入正確的" + tip + "!"); } public static void main(String[] args) { // 代碼生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); //項目根目錄 String projectPath = System.getProperty("user.dir"); //用于多個模塊下生成到精確的目錄下(我設(shè)置在桌面) //String projectPath = "C:/Users/xie/Desktop"; //代碼生成目錄 gc.setOutputDir(projectPath + "/src/main/java"); //開發(fā)人員 gc.setAuthor("先謝郭嘉"); // 是否打開輸出目錄(默認值:null) gc.setOpen(false); //實體屬性 Swagger2 注解 gc.setSwagger2(true); // 是否覆蓋已有文件(默認值:false) gc.setFileOverride(true); //把全局配置添加到代碼生成器主類 mpg.setGlobalConfig(gc); // 數(shù)據(jù)源配置 DataSourceConfig dsc = new DataSourceConfig(); //數(shù)據(jù)庫連接 dsc.setUrl("jdbc:mysql://localhost:3306/blog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8"); // 數(shù)據(jù)庫 schema name //dsc.setSchemaName("public"); // 數(shù)據(jù)庫類型 dsc.setDbType(DbType.MYSQL); // 驅(qū)動名稱 dsc.setDriverName("com.mysql.cj.jdbc.Driver"); //用戶名 dsc.setUsername("root"); //密碼 dsc.setPassword("430423"); //把數(shù)據(jù)源配置添加到代碼生成器主類 mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); // 添加這個后 會以一個實體為一個模塊 比如user實體會生成user模塊 每個模塊下都會生成三層 // pc.setModuleName(scanner("模塊名")); // 父包名。如果為空,將下面子包名必須寫全部, 否則就只需寫子包名 pc.setParent("com.xxgg.blog"); // Service包名 pc.setService("service"); // Entity包名 pc.setEntity("entity"); // ServiceImpl包名 pc.setServiceImpl("service.impl"); // Mapper包名 pc.setMapper("mapper"); // Controller包名 pc.setController("controller"); // Mapper.xml包名 pc.setXml("mapper"); // 把包配置添加到代碼生成器主類 mpg.setPackageInfo(pc); // 自定義配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定義輸出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定義配置會被優(yōu)先輸出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱會跟著發(fā)生變化??! return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判斷自定義文件夾是否需要創(chuàng)建 checkDir("調(diào)用默認方法創(chuàng)建的目錄,自定義目錄用"); if (fileType == FileType.MAPPER) { // 已經(jīng)生成 mapper 文件判斷存在,不想重新生成返回 false return !new File(filePath).exists(); } // 允許生成模板文件 return true; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定義輸出模板 //指定自定義模板路徑,注意不要帶上.ftl/.vm, 會根據(jù)使用的模板引擎自動識別 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 數(shù)據(jù)庫表配置 StrategyConfig strategy = new StrategyConfig(); // 數(shù)據(jù)庫表映射到實體的命名策略:下劃線轉(zhuǎn)駝峰 strategy.setNaming(NamingStrategy.underline_to_camel); // 數(shù)據(jù)庫表字段映射到實體的命名策略, 未指定按照 naming 執(zhí)行 strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 實體是否為lombok模型(默認 false) strategy.setEntityLombokModel(true); // 生成 @RestController 控制器 strategy.setRestControllerStyle(true); // 實體類主鍵名稱設(shè)置 strategy.setSuperEntityColumns("id"); // 需要包含的表名,允許正則表達式 // 這里做了輸入設(shè)置 strategy.setInclude(scanner("表名,多個英文逗號分割").split(",")); // 需要排除的表名,允許正則表達式 //strategy.setExclude("***"); // 是否生成實體時,生成字段注解 默認false; strategy.setEntityTableFieldAnnotationEnable(true); // 駝峰轉(zhuǎn)連字符 strategy.setControllerMappingHyphenStyle(true); // 表前綴 strategy.setTablePrefix(pc.getModuleName() + "_"); // 把數(shù)據(jù)庫配置添加到代碼生成器主類 mpg.setStrategy(strategy); // 在代碼生成器主類上配置模板引擎 mpg.setTemplateEngine(new FreemarkerTemplateEngine()); //生成 mpg.execute(); } }
2、pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.xxgg</groupId> <artifactId>blog</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>blog</name> <description>先謝郭嘉的博客——springboot后端</description> <properties> <java.version>1.8</java.version> <mybatis.version>2.1.3</mybatis.version> <mybatis-plus.version>3.4.0</mybatis-plus.version> <generator.version>3.4.0</generator.version> <druid.version>1.1.9</druid.version> <mysql.version>8.0.21</mysql.version> <lombok.version>1.18.12</lombok.version> <knife4j.version>2.0.3</knife4j.version> <validation.version>2.0.1.Final</validation.version> <jackson.version>2.8.9</jackson.version> <freemarker.version>2.3.30</freemarker.version> </properties> <dependencies> <!--代碼生成器,MyBatis-Plus 從 3.0.3 之后移除了代碼生成器與模板引擎的默認依賴,需要手動添加相關(guān)依賴--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>${generator.version}</version> </dependency> <!--freemarker模板引擎--> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>${freemarker.version}</version> </dependency> <!--mybatis-plus(springboot版)--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <!--mybatis持久層--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.version}</version> </dependency> <!--jackson注解jar包,時間格式化注解@JsonFormat就在里面--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!--一些校驗的依賴,不然啟動會報NoClassDefFoundError: javax/validation/constraints/Min--> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>${validation.version}</version> </dependency> <!--SpringBoot單服務(wù)架構(gòu)使用最新版的knife4j依賴,繼承swagger依賴,同時增強UI實現(xiàn)--> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>${knife4j.version}</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> <version>${lombok.version}</version> </dependency> <!--springboot整合druid連接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>${mysql.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3、例子演示
輸入你需要生成的實體類,多個實體類可以用逗號隔開。
生產(chǎn)前的包結(jié)構(gòu)-------------------------------------------------------------------------
生成后的包結(jié)構(gòu)-------------------------------------------------------------------------
生成后的代碼-------------------------------------------------------------------------
/** * @author 先謝郭嘉 * @since 2020-09-30 */ @Data @EqualsAndHashCode(callSuper = false) @TableName("blog") @ApiModel(value="Blog對象", description="") public class Blog implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "主鍵") @TableId(value = "blogId", type = IdType.AUTO) private Long blogId; @ApiModelProperty(value = "標題") @TableField("title") private String title; @ApiModelProperty(value = "內(nèi)容") @TableField("content") private String content; @ApiModelProperty(value = "首圖地址") @TableField("firstPicture") private String firstPicture; @ApiModelProperty(value = "標簽,比如原創(chuàng)、轉(zhuǎn)載、翻譯等") @TableField("tab") private String tab; @ApiModelProperty(value = "瀏覽次數(shù)") @TableField("views") private Integer views; @ApiModelProperty(value = "評論次數(shù)") @TableField("commentCount") private Integer commentCount; @ApiModelProperty(value = "是否開啟贊賞") @TableField("appreciation") private Boolean appreciation; @ApiModelProperty(value = "是否開啟版權(quán)聲明") @TableField("shareStatement") private Boolean shareStatement; @ApiModelProperty(value = "是否開啟評論") @TableField("commentBled") private Boolean commentBled; @ApiModelProperty(value = "是否發(fā)布") @TableField("published") private Boolean published; @ApiModelProperty(value = "是否推薦") @TableField("recommend") private Boolean recommend; @ApiModelProperty(value = "創(chuàng)建時間") @TableField("createTime") private LocalDate createTime; @ApiModelProperty(value = "更新時間") @TableField("updateTime") private LocalDate updateTime; @ApiModelProperty(value = "博客描述") @TableField("description") private String description; @ApiModelProperty(value = "分類id") @TableField("typeId") private Long typeId; @ApiModelProperty(value = "用戶id") @TableField("userId") private Long userId; }
到此這篇關(guān)于Mybatis-plus 代碼生成器 AutoGenerator 的簡介和使用的文章就介紹到這了,更多相關(guān)Mybatis-plus AutoGenerator使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java swing實現(xiàn)音樂播放器桌面歌詞字體變色效果
這篇文章主要為大家詳細介紹了Java swing實現(xiàn)音樂播放器桌面歌詞字體變色效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-06-06Java中Timer的schedule()方法參數(shù)詳解
今天小編就為大家分享一篇關(guān)于Java中Timer的schedule()方法參數(shù)詳解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03Java使用Kaptcha實現(xiàn)簡單的驗證碼生成器
這篇文章主要為大家詳細介紹了Java如何使用Kaptcha實現(xiàn)簡單的驗證碼生成器,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考下2024-02-02