java automatic code generation

1 Overview

The code can be automatically generated online, eliminating the cumbersome process of copying and modifying the general template code, and reducing the development workload of the team by more than 70%

The java-based template engine velocity, after defining the template file, dynamically generates java, xml, html, sql and other code files that adapt to the business

2. Automatic generation process

First introduce the pom dependency of velocity

        <dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<artifactId>velocity</artifactId>
			<groupId>org.apache.velocity</groupId>
			<version>1.7</version>
		</dependency>

Among them, commons-io is the related framework of io flow.

In the Resources directory, first define the template file template/User.java.vm

package com.yrr.mvntest;

import java.util.Date;
/**
 * ${comments}
 */
@Data
public class ${className} {

#foreach ($column in $columns)
	/**
	 * $column.comments
	 */
	#if($column.columnName == $pk.columnName)
@TableId
	#end
private $column.attrType $column.attrName;
#end
}

Find the table notes, column notes, table names, field names, field types, etc. of tables and columns through the database, and fill them into the template to generate the required code files (the process of querying the database is omitted here):

import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

@WebServlet("/MvnServlet")
public class MvnServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
      //封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("comments", "表注释");
        map.put("className", "User");
        map.put("priName", "id");
        MvnColumn c1 = new MvnColumn("id","bit","列备注1","id","Integer");
        MvnColumn c2 = new MvnColumn("name","varchar","列备注2","name","String");
        MvnColumn c3 = new MvnColumn("mobile","varchar","列备注3","mobile","String");
        List<MvnColumn> mvnColumns = new ArrayList<>();
        mvnColumns.add(c1);
        mvnColumns.add(c2);
        mvnColumns.add(c3);
        map.put("columns", mvnColumns);
        VelocityContext context = new VelocityContext(map);
        StringWriter sw = new StringWriter();
        Template tpl = Velocity.getTemplate("template/User.java.vm", "UTF-8");
        tpl.merge(context, sw);//将数据context合并入模板tpl中,获得的数据写入sw
        
        OutputStream ouputStream = response.getOutputStream();
        IOUtils.write(sw.toString(), ouputStream, "UTF-8");
        IOUtils.closeQuietly(sw);
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=User.java");
	}
}
public class MvnColumn {
	
    private String columnName;
    private String dataType;
    private String comments;
    
    private String attrName;
    private String attrType;
    
    public MvnColumn(String columnName, String dataType, String comments, String attrName, String attrType){
    	this.columnName = columnName;
    	this.dataType = dataType;
    	this.comments = comments;
    	this.attrName = attrName;
    	this.attrType = attrType;
    }
    
    public String getColumnName() {
		return columnName;
	}
	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}
	public String getDataType() {
		return dataType;
	}
	public void setDataType(String dataType) {
		this.dataType = dataType;
	}
	public String getComments() {
		return comments;
	}
	public void setComments(String comments) {
		this.comments = comments;
	}
	public String getAttrName() {
		return attrName;
	}
	public void setAttrName(String attrName) {
		this.attrName = attrName;
	}
	public String getAttrType() {
		return attrType;
	}
	public void setAttrType(String attrType) {
		this.attrType = attrType;
	}
}

You can download the User.java code file on the web client, and the content of the file is as follows:

Under normal circumstances, multiple code files will be generated and packaged into compressed files for download:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

@WebServlet("/MvnServlet")
public class MvnServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	byte[] data = this.generatorCode();
		response.reset();  
        response.setHeader("Content-Disposition", "attachment; filename=\"mvntest.zip\"");  
        response.addHeader("Content-Length", "" + data.length);  
        response.setContentType("application/octet-stream; charset=UTF-8");  
        IOUtils.write(data, response.getOutputStream());
	}
    
    public byte[] generatorCode(){
    	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
      //获取模板列表
        String[] templates = {"template/User.java.vm"};
        for (String template : templates) {
        	Properties prop = new Properties();
            prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            Velocity.init(prop);
          //封装模板数据
            Map<String, Object> map = new HashMap<>();
            map.put("comments", "表注释");
            map.put("className", "User");
            map.put("priName", "id");
            MvnColumn c1 = new MvnColumn("id","bit","列备注1","id","Integer");
            MvnColumn c2 = new MvnColumn("name","varchar","列备注2","name","String");
            MvnColumn c3 = new MvnColumn("mobile","varchar","列备注3","mobile","String");
            List<MvnColumn> mvnColumns = new ArrayList<>();
            mvnColumns.add(c1);
            mvnColumns.add(c2);
            mvnColumns.add(c3);
            map.put("columns", mvnColumns);
            VelocityContext context = new VelocityContext(map);
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                //添加到zip
                zip.putNextEntry(new ZipEntry("main/java/com/yrr/mvntest/User.java"));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
}

The following compressed files can be obtained by accessing on the web client:

Open source project reference: renren-generator: a code generator for Renren open source projects, which can generate entity, xml, dao, service, vue, sql codes online, reducing development tasks by more than 70%

Guess you like

Origin blog.csdn.net/Yang_RR/article/details/127985355