文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2024-04-02 19:55

关注

原理

其原理如图:

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;


@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;


@Service
public class ${moduleClass}Service {

    @Autowired
    private ${moduleClass}Dao ${moduleVar}Dao;

    
    public ${moduleClass}Entity getById(Long id){
        return  ${moduleVar}Dao.selectById(id);
    }

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

    
    public ResponseDTO<String> add(${moduleClass}AddDTO addDTO) {
        ${moduleClass}Entity entity = SmartBeanUtil.copy(addDTO, ${moduleClass}Entity.class);
        ${moduleVar}Dao.insert(entity);
        return ResponseDTO.succ();
    }

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

    
    @Transactional(rollbackFor = Exception.class)
    public ResponseDTO<String> deleteByIds(List<Long> idList) {
        ${moduleVar}Dao.deleteByIdList(idList);
        return ResponseDTO.succ();
    }

    
    public List<${moduleClass}ExcelVO> queryAllExportData(${moduleClass}QueryDTO queryDTO) {
        return ${moduleVar}Dao.queryAllExportData( queryDTO);
    }

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

}

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

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯