Java|Java 如何使用Velocity引擎生成代码

目录

  • 原理
  • 实战

原理 Java|Java 如何使用Velocity引擎生成代码
文章图片

其原理如图:
1.配置数据源信息(包括表名)
2.读取数据表字段信息:列名、类型、字段注释、表注释
【Java|Java 如何使用Velocity引擎生成代码】3.编写代码模板,并将该模板加载到内存
4.根据模板所需,组装Velocity引擎渲染所需字段Map
5.创建Velocity上下文,将代码模板和替换字段传入
6.velocity上下文创建引擎,执行merge合并替换并将最终代码写入文件

实战
1.通过maven构建项目,引入依赖:
velocityorg.apache.velocitycommons-collectionscommons-collectionsorg.apache.velocityvelocity-engine-core

2.在resources/templates/codegenerator目录下面编写代码模板:
VO:
package ${basePackage}.module.${modulePackage}.domain.vo; import lombok.Data; #foreach ($dtoImport in $dtoImports)$dtoImport#endimport com.fasterxml.jackson.annotation.JsonFormat; import io.swagger.annotations.ApiModelProperty; /** *[ ${tableDesc} ] * * @author ${author} * @version 1.0 * @company ${company} * @copyright (c) ${company}Inc. All rights reserved. * @date${date} * @since JDK1.8 */@Datapublic class ${moduleClass}VO {#foreach ($column in $columnList)#if($column.fieldType == 'Date')@ApiModelProperty("${column.columnDesc}")@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")private $column.fieldType $column.fieldName; #else@ApiModelProperty("${column.columnDesc}")private $column.fieldType $column.fieldName; #end#end}

SERVICE:
package ${basePackage}.module.${modulePackage}.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import ${basePackage}.common.domain.PageResultDTO; import ${basePackage}.common.domain.ResponseDTO; import ${basePackage}.module.${modulePackage}.dao.${moduleClass}Dao; import ${basePackage}.module.${modulePackage}.domain.dto.${moduleClass}AddDTO; import ${basePackage}.module.${modulePackage}.domain.dto.${moduleClass}UpdateDTO; import ${basePackage}.module.${modulePackage}.domain.dto.${moduleClass}QueryDTO; import ${basePackage}.module.${modulePackage}.domain.entity.${moduleClass}Entity; import ${basePackage}.module.${modulePackage}.domain.vo.${moduleClass}VO; import ${basePackage}.module.${modulePackage}.domain.vo.${moduleClass}ExcelVO; import ${basePackage}.util.SmartPageUtil; import ${basePackage}.util.SmartBeanUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * [ ${tableDesc} ] * * @author ${author} * @version 1.0 * @company ${company} * @copyright (c)${company}Inc. All rights reserved. * @date ${date} * @since JDK1.8 */@Servicepublic class ${moduleClass}Service {@Autowiredprivate ${moduleClass}Dao ${moduleVar}Dao; /*** 根据id查询*/public ${moduleClass}Entity getById(Long id){return${moduleVar}Dao.selectById(id); }/*** 分页查询* @author ${author}* @date ${date}*/public ResponseDTO> queryByPage(${moduleClass}QueryDTO queryDTO) {Page page = SmartPageUtil.convert2QueryPage(queryDTO); IPage<${moduleClass}VO> voList = ${moduleVar}Dao.queryByPage(page, queryDTO); PageResultDTO<${moduleClass}VO> pageResultDTO = SmartPageUtil.convert2PageResult(voList); return ResponseDTO.succData(pageResultDTO); }/*** 添加* @author ${author}* @date ${date}*/public ResponseDTO add(${moduleClass}AddDTO addDTO) {${moduleClass}Entity entity = SmartBeanUtil.copy(addDTO, ${moduleClass}Entity.class); ${moduleVar}Dao.insert(entity); return ResponseDTO.succ(); }/*** 编辑* @author ${author}* @date ${date}*/@Transactional(rollbackFor = Exception.class)public ResponseDTO update(${moduleClass}UpdateDTO updateDTO) {${moduleClass}Entity entity = SmartBeanUtil.copy(updateDTO, ${moduleClass}Entity.class); ${moduleVar}Dao.updateById(entity); return ResponseDTO.succ(); }/*** 删除* @author ${author}* @date ${date}*/@Transactional(rollbackFor = Exception.class)public ResponseDTO deleteByIds(List idList) {${moduleVar}Dao.deleteByIdList(idList); return ResponseDTO.succ(); }/*** 查询全部导出对象* @author ${author}* @date ${date}*/public List<${moduleClass}ExcelVO> queryAllExportData(${moduleClass}QueryDTO queryDTO) {return ${moduleVar}Dao.queryAllExportData( queryDTO); }/*** 批量查询导出对象* @author ${author}* @date ${date}*/public List<${moduleClass}ExcelVO> queryBatchExportData(List idList) {return ${moduleVar}Dao.queryBatchExportData(idList); }}

Mapper:
select#foreach($column in $columnList)#if($velocityCount != $columnList.size())$column.columnName,#else$column.columnName#end#endfrom ${tableName}#foreach($queryField in $queryFieldList)#if ($queryField.sqlOperate == 'like')AND INSTR($queryField.columnName,#{queryDTO.$queryField.fieldName})#end#if ($queryField.sqlOperate == 'equals')#if ($queryField.fieldType == 'String')AND $queryField.columnName = #{queryDTO.$queryField.fieldName}#elseAND $queryField.columnName = #{queryDTO.$queryField.fieldName}#end#end#if ($queryField.sqlOperate == 'in')and $queryField.columnName in#{item}#end#endAND create_time >= #{queryDTO.createTimeBegin}AND create_time <= #{queryDTO.createTimeEnd}AND update_time >= #{queryDTO.updateTimeBegin}AND update_time <= #{queryDTO.updateTimeEnd}select#foreach($column in $columnList)#if($velocityCount != $columnList.size())$column.columnName,#else$column.columnName#end#endfrom ${tableName}#foreach($queryField in $queryFieldList)#if ($queryField.sqlOperate == 'like')AND INSTR($queryField.columnName,#{queryDTO.$queryField.fieldName})#end#if ($queryField.sqlOperate == 'equals')#if ($queryField.fieldType == 'String')AND $queryField.columnName = #{queryDTO.$queryField.fieldName}#elseAND $queryField.columnName = #{queryDTO.$queryField.fieldName}#end#end#if ($queryField.sqlOperate == 'in')and $queryField.columnName in#{item}#end#endAND create_time >= #{queryDTO.createTimeBegin}AND create_time <= #{queryDTO.createTimeEnd}AND update_time >= #{queryDTO.updateTimeBegin}AND update_time <= #{queryDTO.updateTimeEnd}select#foreach($column in $columnList)#if($velocityCount != $columnList.size())$column.columnName,#else$column.columnName#end#endfrom ${tableName}where id in#{item}delete from ${tableName} where id = #{id}delete from ${tableName} where id in#{item}

3.查询表信息:
selecttable_commentfrom information_schema.tableswhere table_schema = (select database()) and table_name = #{tableName}selectcolumn_name as columnName,data_type as columnType,column_comment as columnDescfrom information_schema.columnswhere table_schema = (select database()) ANDtable_name = #{tableName} order by ordinal_position

4.加载模板、组装数据
public Map codeTemplates(String moduleClass, String basePackage, String modulePackage) {String basePath = basePackage.replaceAll("\\.", File.separator ); String modulePath = modulePackage.replaceAll("\\.", File.separator ); String javaPackagePath = "java" + File.separator + basePath + File.separator + modulePath + File.separator; String xmlPackagePath = "mapper" + File.separator + modulePath + File.separator; String frontPackagePath = "web" + File.separator; Map templateMap = new HashMap<>(); //后端templateMap.put("templates/codegenerator/java/Controller.java.vm", javaPackagePath + "controller" + File.separator + moduleClass + "Controller.java" ); templateMap.put("templates/codegenerator/java/Dao.java.vm", javaPackagePath + "dao" + File.separator + moduleClass + "Dao.java" ); templateMap.put("templates/codegenerator/java/Dao.xml.vm", xmlPackagePath + moduleClass + "Mapper.xml" ); templateMap.put("templates/codegenerator/java/AddDTO.java.vm", javaPackagePath + "domain" + File.separator + "dto" + File.separator + moduleClass + "AddDTO.java" ); templateMap.put("templates/codegenerator/java/UpdateDTO.java.vm", javaPackagePath + "domain" + File.separator + "dto" + File.separator + moduleClass + "UpdateDTO.java" ); templateMap.put("templates/codegenerator/java/Entity.java.vm", javaPackagePath + "domain" + File.separator + "entity" + File.separator + moduleClass + "Entity.java" ); templateMap.put("templates/codegenerator/java/VO.java.vm", javaPackagePath + "domain" + File.separator + "vo" + File.separator + moduleClass + "VO.java" ); templateMap.put("templates/codegenerator/java/ExcelVO.java.vm", javaPackagePath + "domain" + File.separator + "vo" + File.separator + moduleClass + "ExcelVO.java" ); templateMap.put("templates/codegenerator/java/QueryDTO.java.vm", javaPackagePath + "domain" + File.separator + "dto" + File.separator + moduleClass + "QueryDTO.java" ); templateMap.put("templates/codegenerator/java/Service.java.vm", javaPackagePath + "service" + File.separator + moduleClass + "Service.java" ); //前端String webPackageName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, moduleClass).replaceAll("_", "-" ); templateMap.put("templates/codegenerator/web/Api.js.vm", frontPackagePath + "api" + File.separator + webPackageName + ".js" ); templateMap.put("templates/codegenerator/web/Router.js.vm", frontPackagePath + "router" + File.separator + webPackageName + ".js" ); templateMap.put("templates/codegenerator/web/List.vue.vm", frontPackagePath + webPackageName + File.separator + webPackageName + "-list.vue" ); templateMap.put("templates/codegenerator/web/ListForm.vue.vm", frontPackagePath + webPackageName + File.separator + "components" + File.separator + webPackageName + "-list-form.vue" ); return templateMap; }

Properties p = new Properties(); p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); p.put("directive.foreach.counter.name", "velocityCount"); p.put("directive.foreach.counter.initial.value", "1"); Velocity.init(p); Map map = new HashMap<>(); map.put("company", codeGenerator.getCompany()); map.put("tableName", codeGenerator.getTableName()); map.put("basePackage", basePackage); map.put("modulePackage", modulePackage); map.put("moduleClass", moduleClass); map.put("tableDesc", tableDesc); map.put("author", author); map.put("date", date); map.put("moduleVar", moduleVar); map.put("columnList", columnList); map.put("queryFieldList", queryFieldList); map.put("queryImports", queryImports); map.put("dtoImports", dtoImports); map.put("entityImports", entityImports); map.put("webModuleName", CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, moduleClass).replaceAll("_", "-")); map.put("upperCamel", CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, moduleClass)); //前端的变量map.put("ViewUIMessage", "$Message"); map.put("VueRefs", "$refs");

5.创建Velocity上下文,生成代码
VelocityContext context = new VelocityContext(map); private void codeGenerator(VelocityContext context, Map codeTemplates) throws Exception {String projectPath = getOutputDir(); Velocity.setProperty("input.encoding", "UTF-8"); Velocity.setProperty("output.encoding", "UTF-8"); for (Entry entry : codeTemplates.entrySet()) {String template = entry.getKey(); String filePath = projectPath + entry.getValue(); String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1); String fileDir = filePath.replace(fileName, ""); File directory = new File(fileDir); if (!directory.exists()) {directory.mkdirs(); }FileWriter writer; try {writer = new FileWriter(filePath); Template tpl = Velocity.getTemplate(template, "UTF-8"); tpl.merge(context, writer); writer.flush(); writer.close(); } catch (Exception e) {log.error("", e); }}}

以上就是如何使用Velocity引擎生成代码的详细内容,更多关于使用Velocity引擎生成代码的资料请关注脚本之家其它相关文章!

    推荐阅读