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

网友投稿 773 2022-10-18


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

select

#foreach($column in $columnList)

#if($velocityCount != $columnList.size())

$column.columnName,

#else

$column.columnName

#end

#end

from ${tableName}

#foreach($queryField in $queryFieldList)

#if ($queryField.sqlOperate == 'like')

AND INSTR($queryField.columnName,#{queryDTO.$queryField.fieldName})

#end

#if ($queryField.sqlOperate == 'equals')

#if ($queryField.fieldType == 'String')

AND $queryField.columnName = #{queryDTO.$queryField.fieldName}

#else

AND $queryField.columnName = #{queryDTO.$queryField.fieldName}

#end

#end

#if ($queryField.sqlOperate == 'in')

and $queryField.columnName in

#{item}

#end

#end

AND create_time >= #{queryDTO.createTimeBegin}

AND create_time <= #{queryDTO.createTimeEnd}

AND update_time >= #{queryDTO.updateTimeBegin}

AND update_time >= #{queryDTO.updateTimeBegin}

AND update_time <= #{queryDTO.updateTimeEnd}

select

#foreach($column in $columnList)

#if($velocityCount != $columnList.size())

$column.columnName,

#else

$column.columnName

#end

#end

from ${tableName}

#foreach($queryField in $queryFieldList)

#if ($queryField.sqlOperate == 'like')

AND INSTR($queryField.columnName,#{queryDTO.$queryField.fieldName})

#end

#if ($queryField.sqlOperate == 'equals')

#if ($queryField.fieldType == 'String')

AND $queryField.columnName = #{queryDTO.$queryField.fieldName}

#else

AND $queryField.columnName = #{queryDTO.$queryField.fieldName}

#end

#end

#if ($queryField.sqlOperate == 'in')

and $queryField.columnName in

#{item}

#end

#end

AND create_time >= #{queryDTO.createTimeBegin}

AND create_time <= #{queryDTO.createTimeEnd}

AND update_time >= #{queryDTO.updateTimeBegin}

AND update_time <= #{queryDTO.updateTimeEnd}

select

#foreach($column in $columnList)

#if($velocityCount != $columnList.size())

$column.columnName,

#else

$column.columnName

#end

#end

from ${tableName}

where id in

#{item}

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

delete from ${tableName} where id in

#{item}

3.查询表信息:

select

table_comment

from information_schema.tables

where table_schema = (select database()) and table_name = #{tableName}

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

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

}

}

}

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


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:客户端软件的未来之路
下一篇:杨亦涛老师分享SEO的概念,分类,应用和职位
相关文章

 发表评论

暂时没有评论,来抢沙发吧~