使用freemarker编写代码生成器

pom.xml文件引入freemarker和jdbc依赖

<dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.16</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.22</version>
</dependency>

模板文件module.ftl, 所在位置classpath下的module中

package cn.code.bean;

public class ${myClass.className} {

    <#list myClass.fieldList as field>
        //${field.fieldRemarks}
        private ${field.fieldType} ${field.fieldName};
    </#list>

    <#list myClass.fieldList as field>
        public ${field.fieldType} get${field.fieldNameUpperFirstLetter}() {
            return ${field.fieldName};
        }

        public void set${field.fieldNameUpperFirstLetter}(${field.fieldType} ${field.fieldName}) {
            this.${field.fieldName} = ${field.fieldName};
        }
    </#list>
}

属性类Field.class

package cn.code.generate;

//属性类
public class Field {
    //字段名
    private String fieldName;
    //字段类型
    private String fieldType;
    //字段注释
    private String fieldRemarks;
    //字段名首字母大写
    private String fieldNameUpperFirstLetter;

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public String getFieldType() {
        return fieldType;
    }

    public void setFieldType(String fieldType) {
        this.fieldType = fieldType;
    }

    public String getFieldRemarks() {
        return fieldRemarks;
    }

    public void setFieldRemarks(String fieldRemarks) {
        this.fieldRemarks = fieldRemarks;
    }

    public String getFieldNameUpperFirstLetter() {
        return fieldNameUpperFirstLetter;
    }

    public void setFieldNameUpperFirstLetter(String fieldNameUpperFirstLetter) {
        this.fieldNameUpperFirstLetter = fieldNameUpperFirstLetter;
    }
}

MyClass.java

package cn.code.generate;

import java.util.List;

public class MyClass {
    //类名
    private String className;
    //字段的集合
    private List<Field> fieldList;

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public List<Field> getFieldList() {
        return fieldList;
    }

    public void setFieldList(List<Field> fieldList) {
        this.fieldList = fieldList;
    }
}

ClassGenerator.class

package cn.code.generate;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class ClassGenerator {

    public DatabaseMetaData init(){
        DatabaseMetaData databaseMetaData = null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://192.168.126.133:3306/itrip";
            String user = "root";
            String password = "123456";
            Connection connection = DriverManager.getConnection(url, user, password);
            databaseMetaData = connection.getMetaData();
        }catch (Exception e){
            e.printStackTrace();
        }
        return databaseMetaData;
    }

    //根据表名生产出类
    public MyClass generateClass(String tableName){
        MyClass myClass = new MyClass();
        List<Field> fieldList = new ArrayList<Field>();
        DatabaseMetaData databaseMetaData = init();
        try{
            ResultSet rs = databaseMetaData.getColumns(null, "%", tableName, "%");
            while(rs.next()){
                //列名
                String columnName = rs.getString("COLUMN_NAME");
                //类型
                String typeName = rs.getString("TYPE_NAME");
                System.out.println("typeName:" + typeName);
                //注释
                String remarks = rs.getString("REMARKS");

                Field field = new Field();
                field.setFieldName(columnName);
                field.setFieldType(columnTypeToFieldType(typeName));
                field.setFieldRemarks(remarks);
                field.setFieldNameUpperFirstLetter(upperFirstLetter(columnName));
                fieldList.add(field);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        myClass.setClassName(tableNameToClassName(tableName));
        myClass.setFieldList(fieldList);

        return myClass;
    }

    //字段类型转换成属性类型
    public String columnTypeToFieldType(String columnType){
        String fieldType = null;
        switch (columnType) {
            case "INT":
                fieldType = "Integer";
                break;
            case "VARCHAR":
                fieldType = "String";
                break;
            case "CHAR":
                fieldType = "String";
                break;
            case "DATE":
                fieldType = "Date";
                break;
            case "BIGINT":
                fieldType = "Long";
                break;
            default:
                fieldType = "String";
                break;
        }
        return fieldType;
    }

    //首字母大写
    public String upperFirstLetter(String src){
        String firstLetter = src.substring(0, 1).toUpperCase();
        String otherLetters = src.substring(1);
        return firstLetter + otherLetters;
    }

    //表名转类名
    public String tableNameToClassName(String tableName){
        StringBuilder className = new StringBuilder();
        //aa_bb_cc  AaBbCc
        String[] split = tableName.split("_");
        for (String item : split) {
            className.append(upperFirstLetter(item));
        }
        return className.toString();
    }
}

Generator.class

package cn.code.generate;

import cn.code.User;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Generator {

    public static void main(String[] args) throws Exception{
        //创建Configuration对象
        Configuration configuration = new Configuration();
        //设置模板所在目录
        String path = Generator.class.getClassLoader().getResource("module").getPath();
        configuration.setDirectoryForTemplateLoading(new File(path));
        //获取模板
        Template template = configuration.getTemplate("class.ftl");
        //设置数据并执行
        Map map = new HashMap();

        ClassGenerator classGenerator = new ClassGenerator();
        MyClass myClass = classGenerator.generateClass("user");

        map.put("myClass", myClass);

        Writer writer = new OutputStreamWriter(new FileOutputStream("G:/"+myClass.getClassName()+".java"));

        template.process(map, writer);
    }
}



阅读更多
个人分类: freemarker
上一篇使用JDBC获取数据库表的信息
下一篇quartz定时器-SimpleScheduleBuilder
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭