为了代码更加直观和易于调用,实现代码生成共有两个类组成:
(1)配置统一调用入口类GeneratorFacade
/**
* 1.根据传入数据库信息构造数据
* 2.根据模板完成代码生成
*/
public class GeneratorFacade {
private Generator generator;
//公共数据Map集合(处理文件路径等公共代码替换)
private Map<String,Object> commonMap;
public GeneratorFacade(String templatePath, String outPath, Settings settings) {
commonMap = settings.getSettingMap();
commonMap.putAll(PropertiesUtils.customMap);
try {
generator = new Generator(templatePath,outPath);
}catch (Exception e){
}
}
//针对数据库表生成
public void generatorByTable(DataBase db,String tableName) throws Exception {
//查询数据库获取所有表信息
List<Table> tableList = DataBaseUtils.getDbInfo(db, tableName);
for (Table table : tableList) {
//根据数据库表信息,构造数据模型并生成代码
generator.scanTemplatesAndProcess(getTemplateModel(table));
}
}
//根据数据库对象table构造数据模型
private Map getTemplateModel(Table table) {
Map<String,Object> templateMap = new HashMap();
//table表信息
templateMap.put("table",table);
//实体类名称
String prefixs = (String) commonMap.get("tableRemovePrefixes");
String className = table.getName();
for(String prefix : prefixs.split(",")) {
className = StringUtils.removePrefix(className, prefix,true);
}
templateMap.put("ClassName",
StringUtils.makeAllWordFirstLetterUpperCase(className));
//公共的配置和自定义配置
templateMap.putAll(commonMap);
return templateMap;
}
}
(2)处理模板代码生成的核心类Generator
public class Generator {
//模板所在路径
private String templatePath;
//代码生成路径
private String outPath;
private Configuration conf;
public Generator(String templatePath, String outPath) throws Exception {
this.templatePath = templatePath;
this.outPath = outPath;
//创建freemarker的核心配置类
conf = new Configuration();
//指定模板加载器
conf.setTemplateLoader(new FileTemplateLoader(new File(templatePath)));
}
//扫描所有模板并进行代码生成
public void scanTemplatesAndProcess(Map dataMap) throws Exception {
//加载文件夹下的所有模板文件
List<File> srcFiles = FileUtils.searchAllFile(new File(templatePath));
//针对每一个模板文件进行代码生成
for(File srcFile :srcFiles) {
executeGenerate(dataMap, srcFile);
}
}
//对某个模板生成代码
private void executeGenerate(Map dataMap ,File srcFile) throws Exception {
//获取文件路径
String templateFile = srcFile.getAbsolutePath().replace(this.templatePath,"");
//对文件名称进行处理(字符串替换)
String outputFilepath = processTemplateString(templateFile,dataMap);
//读取模板
Template template = conf.getTemplate(templateFile);
//设置字符集
template.setOutputEncoding("encode");
//创建文件
File outFile = FileUtils.mkdir(outPath,outputFilepath);
FileWriter fileWriter = new FileWriter(outFile);
//模板生成
template.process(dataMap,fileWriter);
fileWriter.close();
}
}
使用字符串模板对文件生成路径进行统一处理
//处理字符串模板
private String processTemplateString(String templateString,Map dataMap) throws
Exception {
StringWriter out = new StringWriter();
Template template = new Template("ts",new StringReader(templateString),conf);
template.process(dataMap, out);
return out.toString();
}