一聚教程网:一个值得你收藏的教程网站

热门教程

Java使用Velocity引擎生成代码实例

时间:2022-06-29 02:21:51 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Java使用Velocity引擎生成代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

原理

其原理如图:

1.配置数据源信息(包括表名)

2.读取数据表字段信息:列名、类型、字段注释、表注释

3.编写代码模板,并将该模板加载到内存

4.根据模板所需,组装Velocity引擎渲染所需字段Map

5.创建Velocity上下文,将代码模板和替换字段传入

6.velocity上下文创建引擎,执行merge合并替换并将最终代码写入文件

实战

1.通过maven构建项目,引入依赖:


    velocity
    org.apache.velocity
    
        
            commons-collections
            commons-collections
        
    


    org.apache.velocity
    velocity-engine-core

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> 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:





    
    


    

    

    

    
        delete from ${tableName} where id = #{id}
    

    
        delete from ${tableName} where id in
        
            #{item}
        
    


3.查询表信息:



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);
        }
    }

}

热门栏目