若依代码生成原理:
1、所要操作的表在数据库中存在的形式
在数据库中,操作表直接在ry数据库创建,并且将该表的基本信息保存在gen_table表中,而该表的列保存在gen_table_column表中,这是为了方便生成代码
2、通过使用velocity生成java、sql等代码
关键代码都类似如下(例如:请求路径为/download/{tableName})
private void generatorCode(String tableName, ZipOutputStream zip)
{
// 查询表信息
GenTable table = genTableMapper.selectGenTableByName(tableName);
...
VelocityInitializer.initVelocity();
VelocityContext context = VelocityUtils.prepareContext(table);
// 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates)
{
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, Constants.UTF8);
tpl.merge(context, sw);
try
{
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table)));
IOUtils.write(sw.toString(), zip, Constants.UTF8);
IOUtils.closeQuietly(sw);
zip.flush();
zip.closeEntry();
}
catch (IOException e)
{
log.error("渲染模板失败,表名:" + table.getTableName(), e);
}
}
}