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

}

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

猜你在找的Java 如何使用Velocity引擎生成代码相关文章

代码生成器,可以有效减少编写重复代码,快速实现简单的业务逻辑,也能让我们的代码保持一致。那目前,我们看到的代码生成器,大部分是基于velocity引擎模板生成的,接下来我
今天给大家带来的是关于Java的相关知识总结,文章围绕着JAVA正则表达式及字符串的替换与分解展开,文中有非常详细的介绍及代码示例,需求的大佬可以参考下
了SpringBoot与Postman实现REST模拟请求的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
我们知道Java是一个面相对象的编程语言,基本类型并不具有对象的性质,为了让基本类型也具有对象的特征,就出现了包装类型,它相当于将基本类型“包装起来”,使得它具有了
要实现自定义的xml配置,需要有两个默认spring配置文件来支持。一个是spring.schemas,一个是spring.handlers,前者是为了验证你自定义的xml配置文件是否符合你的格式
ArrayList基于动态数组实现,在添加和删除的时候存在扩容和缩容这样重新规划数组大小的机制。在ArrayList中,维护Object[] elementData数组来管理元素,但是ArrayList
该教程使用idea开发工具初始化javaweb项目,该运行在tomcat服务器上通过配置项目环境变量保证tomcat正常启动,具体操作配置教程参考下本文
SpringBoot 在项目启动的时候封装了创建对象的方法,无需我们手动配置,接下来通过本文给大家介绍SpringBoot 自动配置原理解析及源码展示,感兴趣的朋友一起看看吧
关于Java并发的通信机制是基于共享内存实现的,线程之间共享程序的公共状态,通过写-读内存中的公共状态进行隐式通信,这对程序员是透明的,我们需要理解其工作机制,以防
IDEA编译的时候乱码,Build Output提示信息乱码,本文就详细的介绍一下解决方法,有需要的同学可以了解一下
Cookies是 web站点放置到你的硬盘上的程序。它们驻留在你的计算机上收集关于你在因特网上所做的一切事情的信息,并且 web站点可以在任何时候读取到Cookies收集到的
本文给大家介绍Mybatis结果集映射一对多简单入门教程,包括搭建数据库环境的过程,idea搭建maven项目的代码详解,本文通过实例代码给大家介绍的非常详细,需要的朋友参考