这篇文章主要讲解了“Java 怎么用Velocity引擎生成代码”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Java 怎么用Velocity引擎生成代码”吧!
原理
实战
其原理如图:
1.配置数据源信息(包括表名)
2.读取数据表字段信息:列名、类型、字段注释、表注释
3.编写代码模板,并将该模板加载到内存
4.根据模板所需,组装Velocity引擎渲染所需字段Map
5.创建Velocity上下文,将代码模板和替换字段传入
6.velocity上下文创建引擎,执行merge合并替换并将最终代码写入文件
1.通过maven构建项目,引入依赖:
<dependency> <artifactId>velocity</artifactId> <groupId>org.apache.velocity</groupId> <exclusions> <exclusion> <artifactId>commons-collections</artifactId> <groupId>commons-collections</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> </dependency>
2.在resources/templates/codegenerator目录下面编写代码模板:
VO:
package ${basePackage}.module.${modulePackage}.domain.vo; import lombok.Data; #foreach ($dtoImport in $dtoImports) $dtoImport #end import 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 */ @Data public 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 */ @Service public class ${moduleClass}Service { @Autowired private ${moduleClass}Dao ${moduleVar}Dao; /** * 根据id查询 */ public ${moduleClass}Entity getById(Long id){ return ${moduleVar}Dao.selectById(id); } /** * 分页查询 * @author ${author} * @date ${date} */ public ResponseDTO<PageResultDTO<${moduleClass}VO>> 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<String> 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<String> 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<String> deleteByIds(List<Long> 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<Long> idList) { return ${moduleVar}Dao.queryBatchExportData(idList); } }
Mapper:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="${basePackage}.module.${modulePackage}.dao.${moduleClass}Dao"> <resultMap id="${moduleClass}VO" type="${basePackage}.module.${modulePackage}.domain.vo.${moduleClass}VO"></resultMap> <resultMap id="${moduleClass}ExcelVO" type="${basePackage}.module.${modulePackage}.domain.vo.${moduleClass}ExcelVO"></resultMap> <select id="queryByPage" resultMap="${moduleClass}VO"> select #foreach($column in $columnList) #if($velocityCount != $columnList.size()) $column.columnName, #else $column.columnName #end #end from ${tableName} <where> #foreach($queryField in $queryFieldList) #if ($queryField.sqlOperate == 'like') <if test="queryDTO.${queryField.fieldName} != null and queryDTO.${queryField.fieldName} != ''"> AND INSTR($queryField.columnName,#{queryDTO.$queryField.fieldName}) </if> #end #if ($queryField.sqlOperate == 'equals') #if ($queryField.fieldType == 'String') <if test="queryDTO.${queryField.fieldName} != null and queryDTO.${queryField.fieldName} != ''"> AND $queryField.columnName = #{queryDTO.$queryField.fieldName} </if> #else <if test="queryDTO.${queryField.fieldName} != null"> AND $queryField.columnName = #{queryDTO.$queryField.fieldName} </if> #end #end #if ($queryField.sqlOperate == 'in') <if test="queryDTO.${queryField.fieldName}List !=null and queryDTO.${queryField.fieldName}List.size() > 0"> and $queryField.columnName in <foreach collection="queryDTO.${queryField.fieldName}List" open="(" index="index" separator="," close=")" item="item"> #{item} </foreach> </if> #end #end <if test="queryDTO.createTimeBegin != null "> AND create_time >= #{queryDTO.createTimeBegin} </if> <if test="queryDTO.createTimeEnd != null "> AND create_time <= #{queryDTO.createTimeEnd} </if> <if test="queryDTO.updateTimeBegin != null "> AND update_time >= #{queryDTO.updateTimeBegin} </if> <if test="queryDTO.updateTimeEnd != null "> AND update_time <= #{queryDTO.updateTimeEnd} </if> </where> </select> <select id="queryAllExportData" resultMap="${moduleClass}ExcelVO"> select #foreach($column in $columnList) #if($velocityCount != $columnList.size()) $column.columnName, #else $column.columnName #end #end from ${tableName} <where> #foreach($queryField in $queryFieldList) #if ($queryField.sqlOperate == 'like') <if test="queryDTO.${queryField.fieldName} != null and queryDTO.${queryField.fieldName} != ''"> AND INSTR($queryField.columnName,#{queryDTO.$queryField.fieldName}) </if> #end #if ($queryField.sqlOperate == 'equals') #if ($queryField.fieldType == 'String') <if test="queryDTO.${queryField.fieldName} != null and queryDTO.${queryField.fieldName} != ''"> AND $queryField.columnName = #{queryDTO.$queryField.fieldName} </if> #else <if test="queryDTO.${queryField.fieldName} != null"> AND $queryField.columnName = #{queryDTO.$queryField.fieldName} </if> #end #end #if ($queryField.sqlOperate == 'in') <if test="queryDTO.${queryField.fieldName}List !=null and queryDTO.${queryField.fieldName}List.size() > 0"> and $queryField.columnName in <foreach collection="queryDTO.${queryField.fieldName}List" open="(" index="index" separator="," close=")" item="item"> #{item} </foreach> </if> #end #end <if test="queryDTO.createTimeBegin != null "> AND create_time >= #{queryDTO.createTimeBegin} </if> <if test="queryDTO.createTimeEnd != null "> AND create_time <= #{queryDTO.createTimeEnd} </if> <if test="queryDTO.updateTimeBegin != null "> AND update_time >= #{queryDTO.updateTimeBegin} </if> <if test="queryDTO.updateTimeEnd != null "> AND update_time <= #{queryDTO.updateTimeEnd} </if> </where> </select> <select id="queryBatchExportData" resultMap="${moduleClass}ExcelVO"> select #foreach($column in $columnList) #if($velocityCount != $columnList.size()) $column.columnName, #else $column.columnName #end #end from ${tableName} where id in <foreach collection="idList" open="(" close=")" separator="," item="item"> #{item} </foreach> </select> <delete id="deleteById"> delete from ${tableName} where id = #{id} </delete> <delete id="deleteByIdList"> delete from ${tableName} where id in <foreach collection="idList" open="(" close=")" separator="," item="item"> #{item} </foreach> </delete> </mapper>
3.查询表信息:
<select id="selectTableDesc" resultType="String"> select table_comment from information_schema.tables where table_schema = (select database()) and table_name = #{tableName} </select> <select id="selectTableColumn" resultMap="ColumnDTO"> select column_name as columnName, data_type as columnType, column_comment as columnDesc from information_schema.columns where table_schema = (select database()) AND table_name = #{tableName} order by ordinal_position </select>
4.加载模板、组装数据
public Map<String, String> 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<String, String> 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<String, Object> 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<String, String> codeTemplates) throws Exception { String projectPath = getOutputDir(); Velocity.setProperty("input.encoding", "UTF-8"); Velocity.setProperty("output.encoding", "UTF-8"); for (Entry<String, String> 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); } } }
感谢各位的阅读,以上就是“Java 怎么用Velocity引擎生成代码”的内容了,经过本文的学习后,相信大家对Java 怎么用Velocity引擎生成代码这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。