- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- Java基礎之教你怎么用代碼一鍵生成POJO
在寫(xiě)SpringBoot項目,有時(shí)候設計到的表有幾十上百張,如果要一個(gè)一個(gè)手動(dòng)創(chuàng )建JavaBean以及對應的mapper類(lèi)的話(huà),雖然支持CV的過(guò)程。但是也讓人很頭大。
好在Myabtis-Plus提供了一個(gè)代碼生成器,可以幫助我們根據表生成對應的controller、service、mapper、entity。
接下來(lái)看看如何使用這個(gè)代碼生成器。
首先在項目中加入代碼生成器的依賴(lài)
當前最新版本是3.4.2
。具體可以到官網(wǎng)去查看。
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.2</version> </dependency>
接著(zhù)要加入模板引擎。默認是使用Velocity。Freemarker、Beetl也可以。
Velocity(默認):
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency>
Freemarker:
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency>
Beetl:
<dependency> <groupId>com.ibeetl</groupId> <artifactId>beetl</artifactId> <version>3.3.2.RELEASE</version> </dependency>
完整代碼在文末。
這個(gè)部分內容不用管。就是用來(lái)讀入一些輸入用的。
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 + "!"); }
用來(lái)設置生成的文件存放位置。默認是在當前項目的目錄下??梢宰孕行薷?。
還可以設置是否加上swagger注解。默認是沒(méi)有的。 需要的話(huà),可以把下方的這個(gè)注釋刪掉。
// 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("jobob"); gc.setOpen(false); // gc.setSwagger2(true); 實(shí)體屬性 Swagger2 注解 mpg.setGlobalConfig(gc);
// 數據源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("密碼");
設置代碼的包名和模塊名
// 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner("模塊名")); pc.setParent("com.baomidou.ant");
模板引擎的設置
根據你選擇的模板引擎,選擇對應的模板引擎路徑。
// 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定義輸出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定義配置會(huì )被優(yōu)先輸出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸出文件名 , 如果你 Entity 設置了前后綴、此處注意 xml 的名稱(chēng)會(huì )跟著(zhù)發(fā)生變化??! return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } });
如果模板引擎不是用默認的Vecity的話(huà)。記得設置對應的模板引擎
// set freemarker engine mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // set beetl engine mpg.setTemplateEngine(new BeetlTemplateEngine()); // set custom engine (reference class is your custom engine class) mpg.setTemplateEngine(new CustomTemplateEngine());
最后設置列名的明明方式、是否加Lombok、使用restController等
// 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setSuperEntityClass("你自己的父類(lèi)實(shí)體,沒(méi)有就不用設置!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父類(lèi) strategy.setSuperControllerClass("你自己的父類(lèi)控制器,沒(méi)有就不用設置!"); // 寫(xiě)于父類(lèi)中的公共字段 strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多個(gè)英文逗號分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_");
// 演示例子,執行 main 方法控制臺輸入模塊表名回車(chē)自動(dòng)生成對應項目目錄中 public class CodeGenerator { /** * <p> * 讀取控制臺內容 * </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"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("jobob"); gc.setOpen(false); // gc.setSwagger2(true); 實(shí)體屬性 Swagger2 注解 mpg.setGlobalConfig(gc); // 數據源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("密碼"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner("模塊名")); pc.setParent("com.baomidou.ant"); 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<>(); // 自定義配置會(huì )被優(yōu)先輸出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定義輸出文件名 , 如果你 Entity 設置了前后綴、此處注意 xml 的名稱(chēng)會(huì )跟著(zhù)發(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("調用默認方法創(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, 會(huì )根據使用的模板引擎自動(dòng)識別 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setSuperEntityClass("你自己的父類(lèi)實(shí)體,沒(méi)有就不用設置!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父類(lèi) strategy.setSuperControllerClass("你自己的父類(lèi)控制器,沒(méi)有就不用設置!"); // 寫(xiě)于父類(lèi)中的公共字段 strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多個(gè)英文逗號分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
到此這篇關(guān)于Java基礎之教你怎么用代碼一鍵生成POJO的文章就介紹到這了,更多相關(guān)Java代碼生成POJO內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站