Java基礎(chǔ)之教你怎么用代碼一鍵生成POJO
一、前言
在寫SpringBoot項(xiàng)目,有時(shí)候設(shè)計(jì)到的表有幾十上百張,如果要一個(gè)一個(gè)手動(dòng)創(chuàng)建JavaBean以及對應(yīng)的mapper類的話,雖然支持CV的過程。但是也讓人很頭大。
好在Myabtis-Plus提供了一個(gè)代碼生成器,可以幫助我們根據(jù)表生成對應(yīng)的controller、service、mapper、entity。

接下來看看如何使用這個(gè)代碼生成器。
二、使用
首先在項(xiàng)目中加入代碼生成器的依賴
當(dāng)前最新版本是3.4.2。具體可以到官網(wǎng)去查看。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.2</version>
</dependency>
接著要加入模板引擎。默認(rèn)是使用Velocity。Freemarker、Beetl也可以。
Velocity(默認(rèn)):
<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è)部分內(nè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 + "!");
}
用來設(shè)置生成的文件存放位置。默認(rèn)是在當(dāng)前項(xiàng)目的目錄下??梢宰孕行薷摹?/p>
還可以設(shè)置是否加上swagger注解。默認(rèn)是沒有的。 需要的話,可以把下方的這個(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);
這個(gè)就是配置數(shù)據(jù)庫的地址、用戶名和密碼了
// 數(shù)據(jù)源配置
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("密碼");
設(shè)置代碼的包名和模塊名
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模塊名"));
pc.setParent("com.baomidou.ant");
模板引擎的設(shè)置
根據(jù)你選擇的模板引擎,選擇對應(yīng)的模板引擎路徑。
// 如果模板引擎是 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 設(shè)置了前后綴、此處注意 xml 的名稱會(huì)跟著發(fā)生變化??!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
如果模板引擎不是用默認(rèn)的Vecity的話。記得設(shè)置對應(yīng)的模板引擎
// 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());
最后設(shè)置列名的明明方式、是否加Lombok、使用restController等
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("你自己的父類實(shí)體,沒有就不用設(shè)置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父類
strategy.setSuperControllerClass("你自己的父類控制器,沒有就不用設(shè)置!");
// 寫于父類中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多個(gè)英文逗號分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
四、完整代碼
// 演示例子,執(zhí)行 main 方法控制臺(tái)輸入模塊表名回車自動(dòng)生成對應(yīng)項(xiàng)目目錄中
public class CodeGenerator {
/**
* <p>
* 讀取控制臺(tái)內(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");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("jobob");
gc.setOpen(false);
// gc.setSwagger2(true); 實(shí)體屬性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
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 設(shè)置了前后綴、此處注意 xml 的名稱會(huì)跟著發(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) {
// 判斷自定義文件夾是否需要?jiǎng)?chuàng)建
checkDir("調(diào)用默認(rèn)方法創(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ì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
// 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("你自己的父類實(shí)體,沒有就不用設(shè)置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父類
strategy.setSuperControllerClass("你自己的父類控制器,沒有就不用設(shè)置!");
// 寫于父類中的公共字段
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基礎(chǔ)之教你怎么用代碼一鍵生成POJO的文章就介紹到這了,更多相關(guān)Java代碼生成POJO內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java和MySQL數(shù)據(jù)庫中關(guān)于小數(shù)的保存問題詳析
在Java和MySQL中小數(shù)的精度可能會(huì)受到限制,如float類型的小數(shù)只能精確到6-7位,double類型也只能精確到15-16位,這篇文章主要給大家介紹了關(guān)于Java和MySQL數(shù)據(jù)庫中關(guān)于小數(shù)的保存問題,需要的朋友可以參考下2024-01-01
使用postman傳遞list集合后臺(tái)springmvc接收
這篇文章主要介紹了使用postman傳遞list集合后臺(tái)springmvc接收的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Java?數(shù)據(jù)結(jié)構(gòu)進(jìn)階二叉樹題集下
二叉樹可以簡單理解為對于一個(gè)節(jié)點(diǎn)來說,最多擁有一個(gè)上級節(jié)點(diǎn),同時(shí)最多具備左右兩個(gè)下級節(jié)點(diǎn)的數(shù)據(jù)結(jié)構(gòu)。本文將帶你通過實(shí)際題目來熟練掌握2022-04-04
SpringBoot內(nèi)置tomcat參數(shù)調(diào)優(yōu)的實(shí)現(xiàn)
springboot內(nèi)置了tomcat, 并給我們設(shè)置了默認(rèn)參數(shù), 我們怎么樣修改springboot內(nèi)置的tomcat參數(shù),本文就詳細(xì)的來介紹一下,感興趣的可以了解一下2023-09-09

