Java代码生成器可以帮助开发人员快速生成常用的Java代码,如数据访问层、业务逻辑层、控制器层等。它可以帮助开发人员更快速、高效地完成开发任务。在Java开发中,代码生成器已经成为了不可或缺的工具之一。本文将介绍Java代码生成器的相关概念、优点和适用场景等方面,并提供Java代码生成器的示例代码。
废话不多说,直接上代码:
public class CodeGen {
private static final String URL = "xxxxx"; //数据库连接地址
private static final String DRIVER_NAME = "oracle.jdbc.OracleDriver";
private static final String USERNAME = "userName"; //usernanme
private static final String PARENT_PACKAGE = "com.xxxx"; //代码生成路径
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setAuthor(scanner("开发者昵称"));
gc.setOpen(false);
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
// 开启实体属性 Swagger2 注解
gc.setSwagger2(true);
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(URL);
dsc.setDriverName(DRIVER_NAME);
dsc.setUsername(USERNAME);
dsc.setPassword(scanner("数据库蜜马"));
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent(PARENT_PACKAGE);
// 目标生成目录
Map<String, String> pathInfo = new HashMap<String, String>(6){{
put("entity_path",projectPath + "/"+ pc.getModuleName() +"/src/main/java/xxx/"+ pc.getModuleName() +"/entity");
put("mapper_path",projectPath + "/"+ pc.getModuleName() +"/src/main/java/xxx/"+ pc.getModuleName() +"/mapper");
put("service_path",projectPath + "/"+ pc.getModuleName() +"/src/main/java/xxx/"+ pc.getModuleName() +"/service");
put("service_impl_path",projectPath + "/"+ pc.getModuleName() +"/src/main/java/xxxx/"+ pc.getModuleName() +"/service/impl");
put("controller_path",projectPath + "/"+ pc.getModuleName() +"/src/main/java/xxx/"+ pc.getModuleName() +"/controller");
put("xml_path",projectPath + "/"+ pc.getModuleName() +"/src/main/resources/mapper");
}};
pc.setPathInfo(pathInfo);
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setEntityTableFieldAnnotationEnable(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(scanner("表前缀,形如tbl_,tb_,sys_等"));
mpg.setStrategy(strategy);
mpg.execute();
}
/**
* 读取控制台内容
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入" + tip + ":");
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
}
以上代码可修改相关配置后直接使用