@Test
void templateDataImport() throws IOException {
Properties prop = new Properties();
prop.put("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(prop);
Velocity.init();
Map<String, Object> map = new HashMap<>();
String dirver = "com.mysql.cj.jdbc.Driver";
String url = "";
String user = "";
String password = "";
String database = "";
String deltaQueryProperties = "DATE_FORMAT(update_time,'%Y-%m-%d %H:%i:%S')";
String table = "custom_user";
String primaryKey = "id";
map.put("driver",dirver);
map.put("url", url);
map.put("user", user);
map.put("password", password);
map.put("table", table);
map.put("primaryKey", primaryKey);
map.put("database", database);
map.put("deltaQueryProperties", deltaQueryProperties);
List<FieldVmConfig> dataConfigFields = new ArrayList<>();
dataConfigFields.add(new FieldVmConfig("id","id"));
dataConfigFields.add(new FieldVmConfig("username","username"));
dataConfigFields.add(new FieldVmConfig("password","password"));
dataConfigFields.add(new FieldVmConfig("gender","gender"));
dataConfigFields.add(new FieldVmConfig("birth","birth"));
dataConfigFields.add(new FieldVmConfig("email","email"));
dataConfigFields.add(new FieldVmConfig("phone","phone"));
dataConfigFields.add(new FieldVmConfig("remark","remark"));
dataConfigFields.add(new FieldVmConfig("createTime","create_time"));
dataConfigFields.add(new FieldVmConfig("updateTime","update_time"));
map.put("dataConfigFields", dataConfigFields);
VelocityContext context = new VelocityContext(map);
context.put("math", new MathTool());
context.put("dateTool", new DateTool());
List<String> templates = Collections.singletonList("template/dataconfig.xml.vm");
Map<String, String> resultMap = new LinkedHashMap<>(8);
for (String template : templates) {
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8.toString());
tpl.merge(context, sw);
FileUtil.writeString(sw.toString(), "dataimport", CharsetUtil.UTF_8);
FileWriter fw = new FileWriter("dataimport.xml");
fw.write(sw.toString());
fw.close();
resultMap.put(template, sw.toString());
}
}
.vm模板文件
<?xml version="1.0" encoding="UTF-8"?>
<dataConfig>
<dataSource type="JdbcDataSource"
driver="${driver}"
url="${url}"
user="${user}"
password="${password}"/>
<document>
<entity name="${table}" pk="id"
query="select ${primaryKey} as id${columns} from ${database}.${table} where deleted ='N' "
deltaImportQuery="select ${primaryKey} as id${columns} from ${database}.${table} where ${primaryKey} = '${dih.delta.id}'"
deltaQuery="select ${primaryKey} from ${database}.${table} where ${convertType}(${updateTimeKey},${timeType}) > '${dih.last_index_time}' and deleted ='N' "
deletedPkQuery="select ${primaryKey} from ${database}.${table} where deleted ='Y'"
>
#foreach ($field in $dataConfigFields)
<field column="$field.columnName" name="$field.name"/>
#end
</entity>
</document>
</dataConfig>