代码生成器专题(准备二):Velocity生成Java文件测试

 1、Entity.java.vm文件编写

package ${package}.${moduleName}.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
#if(${hasBigDecimal})
import java.math.BigDecimal;
#end
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 

* ${comments} *

* * @package: ${package}.${moduleName}.entity * @description: ${comments} * @author: ${author} * @date: Created in ${datetime} * @copyright: Copyright (c) ${year} * @version: V1.0 * @modified: ${author} */ @Data @TableName("${tableName}") @ApiModel(description = "${comments}") @EqualsAndHashCode(callSuper = true) public class ${className} extends Model<${className}> { private static final long serialVersionUID = 1L; #foreach ($column in $columns) /** * $column.comments */ #if($column.columnName == $pk.columnName) @TableId #end @ApiModelProperty(value = "$column.comments") private $column.attrType $column.lowerAttrName; #end }

2、代码生成测试

package com.cx.codegenT.velocity;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

@SpringBootTest
public class VelocityMainT {
    @Test
    public void test() throws FileNotFoundException {
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);

        Template tpl = Velocity.getTemplate("template/Entity.java.vm", CharsetUtil.UTF_8);


        Map map = new HashMap<>(16);

        map.put("package","com.cx.project");
        map.put("moduleName","system");
        map.put("comments","数据库备注信息:用户表");
        map.put("author","P");
        map.put("datetime", DateUtil.date());
        map.put("year",DateUtil.year(new Date()));

        map.put("tableName","sys_user");
        map.put("className","User");



        Map column = new HashMap<>();
        column.put("attrType","String");
        column.put("lowerAttrName","Id");
        column.put("comments","主键id");
        List> columns  = new ArrayList<>();
        columns.add(column);

        map.put("columns",columns);

        map.put("pk.columnName","Id");

        VelocityContext context = new VelocityContext(map);

        PrintWriter pw=new PrintWriter("E:\\CompanyCode\\User.java");
        tpl.merge(context, pw);

        pw.flush();
        pw.close();
    }
}

 

你可能感兴趣的:(代码生成,velocity)