您好,登錄后才能下訂單哦!
這篇文章主要講解了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。