自动生成代码-Velocity引擎-vm文件-参考ruoyi 根据数据库表生成实体类

9 篇文章 0 订阅

根据上篇文章,获取数据库表格信息

https://blog.csdn.net/MinisterOL/article/details/137638912

1、初始化 Velocity引擎

import org.apache.velocity.app.Velocity;
import java.util.Properties;

/**
 * VelocityEngine工厂
 *
 * @author ruoyi
 */
public class VelocityInitializer {

    /**
     * 初始化vm方法
     */
    public static void initVelocity() {
        Properties p = new Properties();
        try {
            // 加载classpath目录下的vm文件
            p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            // 定义字符集
            p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
            p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
            // 初始化Velocity引擎,指定配置Properties
            Velocity.init(p);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

2、设置模板变量信息

import org.apache.velocity.VelocityContext;

/**
* 设置模板变量信息
 *
 * @return 模板列表
 */
public static VelocityContext prepareContext(GenTable genTable) {
    VelocityContext velocityContext = new VelocityContext();
    velocityContext.put("tableName", genTable.getTableName());
    velocityContext.put("tableAlias", genTable.getTableAlias());
    velocityContext.put("tableComment", genTable.getTableComment());
    velocityContext.put("className", genTable.getClassName());
    velocityContext.put("classNoteName", genTable.getClassNoteName());
    velocityContext.put("packageName", genTable.getPackageName());
    velocityContext.put("sysName", genTable.getSysName());
    velocityContext.put("moduleName", genTable.getModuleName());
    velocityContext.put("functionName", genTable.getFunctionName());
    velocityContext.put("functionAuthor", genTable.getFunctionAuthor());
    velocityContext.put("importList", getImportList(genTable));
    velocityContext.put("table", genTable);
    velocityContext.put("controllerMappingPath", genTable.getControllerMappingPath());
    velocityContext.put("datetime", new Date());
    return velocityContext;
}

3、获取模板列表
【此处根据每个项目不同决定】

import java.util.List;

/**
 * 获取模板信息
 *
 * @return 模板列表
 */
public static List<String> listTemplate() {
    List<String> templateList = new ArrayList<>();
    templateList.add("vm/java/entity.java.vm");
    templateList.add("vm/java/mapper.java.vm");
    templateList.add("vm/java/entityPo.java.vm");
    templateList.add("vm/java/entityDo.java.vm");
    templateList.add("vm/java/entityRes.java.vm");
    templateList.add("vm/java/entityReq.java.vm");
    templateList.add("vm/java/service.java.vm");
    templateList.add("vm/java/serviceImpl.java.vm");
    templateList.add("vm/java/bizService.java.vm");
    templateList.add("vm/java/bizServiceImpl.java.vm");
    templateList.add("vm/java/controller.java.vm");
    templateList.add("vm/xml/mapper.xml.vm");
    templateList.add("vm/applet/applet-info.vue.vm");
    templateList.add("vm/applet/applet-query.vue.vm");
    templateList.add("vm/applet/applet-save.vue.vm");
    templateList.add("vm/web/web-save.vue.vm");
    templateList.add("vm/web/web-query.vue.vm");
    templateList.add("vm/web/web-info.vue.vm");
    return templateList;
}

vm文件:

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

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import javax.validation.constraints.NotNull;

import com.internetCafes.spms.common.valid.paramcontroller.ParamValid;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
    #foreach($import in $importList)
    import $import;
    #end

import com.internetCafes.spms.common.base.entity.BaseEntity;

/**
 * ${classNoteName} 对象
 * <p>
 *     ${tableComment}
 * </p>
 *
 * @author ${functionAuthor}
 * @since ${datetime}
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("${tableName}")
public class ${className} extends BaseEntity{

private static final long serialVersionUID=1L;

#foreach ($column in $table.columnList)
/** $column.javaNoteName $column.columnComment */
    #if($column.javaType == 'Date')
    @JsonFormat(pattern = "yyyy-MM-dd")
    #end
    #set($orderNum = $column.sort - 1)
    #if($column.listFlag == 1)
        #if($column.javaType == 'Date')
        @Excel(name = "${column.javaNoteName}", width = 15, needMerge = true, format = "yyyy-MM-dd", orderNum = "$orderNum")
        #else
        @Excel(name = "${column.javaNoteName}", width = 15, needMerge = true, orderNum = "$orderNum")
        #end
    #end
private $column.javaType $column.javaField;

#end

    @Override
    @NotNull(groups = {ParamValid.UpdateGroup.class})
    public Long getId(){
        return super.getId();
    }
}

4、渲染模板
此处 template 为 第三步的模板地址

import org.apache.velocity.Template;
import java.io.StringWriter;

// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, "UTF-8");
tpl.merge(context, sw);

5、这里文件输出到zip

import org.apache.commons.io.IOUtils;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
// 添加到zip
zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, genTable)));
IOUtils.write(sw.toString(), zip, "UTF-8");
IOUtils.closeQuietly(sw);
zip.flush();
zip.closeEntry();

IOUtils.closeQuietly(zip);

6、写出文件信息

String filePath = ".zip";
 File file = new File(filePath);
  if (file.exists()) {
      file.delete();
  }
  FileOutputStream fos = null;
  try {
      fos = new FileOutputStream(file);
      fos.write(data, 0, data.length);
      fos.flush();
      fos.close();
  } catch (FileNotFoundException e) {
      throw new RuntimeException(e);
  } catch (IOException e) {
      throw new RuntimeException(e);
  }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis-Plus是一个在MyBatis基础上进行功能扩展的数据库ORM框架。它提供了自动生成代码的功能,通过定义自定义引擎文件VM文件),我们可以对生成代码进行定制和扩展。 首先,我们需要在项目中创建一个.vm文件,该文件是一个Velocity模板文件,用于生成具体的代码。我们可以根据自己的需求定义不同的模板,然后通过配置MyBatis-Plus,告诉它使用我们自定义的模板。 在.vm文件中,我们可以使用Velocity语法来定义生成代码的格式和内容。例如,我们可以定义实体类的字段名、类型、注释等信息,以及对应的数据库名、列名等信息。另外,我们还可以定义生成文件路径、文件名等。 当配置好自定义引擎文件后,我们需要在MyBatis-Plus的代码生成配置中指明使用哪个引擎文件。配置项包括模板路径、模板名称等。在运行代码生成命令时,MyBatis-Plus会根据配置的引擎文件生成相应的代码文件。 通过自定义引擎文件,我们可以灵活地控制代码生成的结果,满足不同项目的需求。我们可以根据实际情况,修改生成代码的格式、结构或增加一些自定义的内容。这使得生成代码更符合我们项目的规范和要求。 总结来说,自定义引擎文件是MyBatis-Plus自动生成代码功能的关键部分。通过将我们自定义的模板文件与MyBatis-Plus的配置进行合理结合,可以实现对生成代码进行个性化定制,提高开发效率和代码质量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值