欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

FreeMark自动生成代码

程序员文章站 2022-06-15 11:21:39
...

1)环境

 <!--freemarker 生成模版工具-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.16</version>
        </dependency>
        <!--jfinal 类包-->
        <dependency>
            <groupId>com.jfinal</groupId>
            <artifactId>jfinal</artifactId>
            <version>3.1</version>
        </dependency>
        <!--jfinal 类包end-->

等jdbc包


2)程序如下

a)freemark模板

package ${package};
import java.util.Date;
@SuppressWarnings("serial")
public class ${modelName} {
    
    <#list tableColumns as columns>
    <#if columns[2]!="">
        // ${columns[2]} 
        </#if>
    private ${columns[1]} ${columns[4]};
    </#list>

    <#list tableColumns as columns>
        <#if columns[2]!="">
    /** ${columns[2]} */
        </#if>
    public ${columns[1]} get${columns[5]} (){
        return this.${columns[4]};
    }
    
    <#if columns[2]!="">
    /** ${columns[2]} */
    </#if>
    public void set${columns[5]} (${columns[1]} ${columns[4]}){
        this.${columns[4]} = ${columns[4]};
    }

    </#list>
    
    
}


b)DataBaseTypeToJavaType.java

package com.se.utils.gencode;

/**
 * Created by cwq on 2017/9/12.
 * jdk 1.8
 */
public class DataBaseTypeToJavaType {
    public enum MysqlType {
        CHAR("char", "String"), VARCHAR("varchar", "String"), BLOB("blob", "Byte[]"), TEXT("text", "String"), INT("int", "Integer"), TINYINT("tinyint", "Integer"), SMALLINT("smallint", "Integer"), MEDIUMINT("mediumint", "Integer"), BIT("bit", "Boolean"), BIGINT("bigint", "Long"), DECIMAL("decimal", "BigDecimal"), DATE("date", "Date")
//        ,DATETIME("datetime","Timestamp")
        , DATETIME("datetime", "Date")
//        ,TIMESTAMP("timestamp","timestamp")
        , TIMESTAMP("timestamp", "Date"), TIME("time", "Time"), YEAR("year", "Date"), FLOAT("float", "Float"), DOUBLE("double", "Double"), INTEGER("integer", "Long");

        private String key;
        private String value;

        public String getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }

        private MysqlType(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public static MysqlType getByKey(String key) {
            for (MysqlType a : MysqlType.values())
                if (a.getKey().equals(key))
                    return a;
            return null;
        }

    }


    public enum JFinalType {
        String("String", "getStr"), Integer("Integer", "getInt"), Long("Long", "getLong"), BigInteger("BigInteger", "getLong"), Date("Date", "getDate"), Time("Time", "getTime"), Timestamp("Timestamp", "getTimestamp"), Double("Double", "getDouble"), Float("Float", "getFloat"), Boolean("Boolean", "getBoolean"), BigDecimal("BigDecimal", "getBigDecimal"), BYTE("byte[]", "getBytes"), Number("Number", "getNumber");
        private String key;
        private String value;

        public String getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }

        private JFinalType(String key, String value) {
            this.key = key;
            this.value = value;
        }

        public static JFinalType getByKey(String key) {
            for (JFinalType a : JFinalType.values())
                if (a.getKey().equals(key))
                    return a;
            return null;
        }

    }

    public String get(String type) {
        MysqlType mysqlType = MysqlType.getByKey(type);
        if (mysqlType != null)
            return mysqlType.getValue();
        return null;
    }

    public String getJFinal(String type) {
        JFinalType jFinalType = JFinalType.getByKey(type);
        if (jFinalType != null)
            return jFinalType.getValue();
        return null;
    }
}



c)GenCode.java

package com.se.utils.gencode;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import com.mchange.v2.io.FileUtils;
import com.se.utils.PropertyUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.sql.DataSource;
import java.io.*;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by cwq on 2017/9/12.
 * jdk 1.8
 */
public class GenCode {

    public static void main(String[] args) {
//        ArrayList<String[]> list = getTableColumns("b_activity_teacher");
//
//        for (String[] s : list) {
//            System.out.println("key:" + s[0] + ",value:" + s[1] + ",Comment:" + s[2]);
//            System.out.println("jFinalType:" + s[3] + ",camelCase:" + s[4] + ",camelCaseUp:" + s[5]);
//        }
    	String path = "D:\\Workspaces\\MyEclipse 10\\eshop\\domain\\src\\main\\java\\com\\domain\\model";
        createModel("com.domain.model", path,  "t_goods", "id");

    }

    public static void createModel(String tableName) {
        createModel(null, null, tableName, null);
    }

    public static void createModel(String tableName, String pkName) {
        createModel(null, null, tableName, pkName);
    }
    
    /**
     * @param Package   包名
     * @param dir       生成路径
     * @param tableName 表名
     * @param pkName    主键名称
     * @author cwq
     * @date 2017/9/12 下午3:48
     */
    public static void createModel(String Package, String dir, String tableName, String pkName) {
        String className = "model";
        className = upFirstName(camelCase(tableName), 1);
        char sp = File.separatorChar;
        if (Package == null)
            Package = "com.se.model";
        if (pkName == null)
            pkName = "id";
        String baseDir = PathKit.getWebRootPath() + sp + "src" + sp + "main" + sp + "java" + sp + "com" + sp + "se";
        if (dir == null)
            dir = baseDir + sp + "model";
        dir = dir + sp;
        String modelFile = dir + className + ".java";
        try {
            if (new File(modelFile).exists()) {
                System.err.println("文件【" + modelFile + "】已存在!");
            } else {
                StringWriter writer = new StringWriter();
                Map<String, Object> context = new HashMap<String, Object>();
                ArrayList<String[]> tableColumns = getTableColumns(tableName);
                context.put("modelName", className);
                context.put("package", Package);
                context.put("pkName", pkName);
                context.put("tableColumns", tableColumns);
                Configuration configuration = new Configuration();
                //加载渲染目录
                configuration.setDirectoryForTemplateLoading(new File(baseDir + sp + "utils" + sp + "gencode"));
                //加载模版
                Template template = configuration.getTemplate("Model.ftl");
                //替换模版
                template.process(context, writer);
//                渲染模版
                FileUtils.touch(new File(modelFile));
                writeFileContent(modelFile, writer.toString());
                System.out.println("创建文件【" + modelFile + "】成功!");
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    /**
     * 获得表字段
     *
     * @param tableName
     * @return
     * @author cwq
     * @date 2017/9/12 下午5:25
     */
    public static ArrayList<String[]> getTableColumns(String tableName) {
        DataBaseTypeToJavaType dtj = new DataBaseTypeToJavaType();
        Connection conn = null;
        PreparedStatement columnsPs = null;
        try {
            conn = getDataSource().getConnection();
//            获取表的信息
            columnsPs = conn.prepareStatement("show full columns from  " + tableName);
            //字段列表
            ArrayList<String[]> list = new ArrayList<String[]>();
            ResultSet resultSet = columnsPs.executeQuery();
            // 获取对应表中的字段
            while (resultSet.next()) {
                String key = resultSet.getString(1);
                String type = dtj.get(resultSet.getString(2).split("\\(")[0]);
                String note = resultSet.getString(9);
                String jFinalType = dtj.getJFinal(type);//jfinal get 使用方法
                String camelCase = camelCase(key);//字段驼峰式
                String camelCaseUp = upFirstName(camelCase, 1);//字段驼峰式首字母大写
                list.add(new String[]{
                        key
                        , type
                        , note
                        , jFinalType
                        , camelCase
                        , camelCaseUp
                });
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
                columnsPs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param file
     * @param conent
     * @author cwq
     * @date 2017/9/12 下午3:42
     * 写入流
     */
    public static void writeFileContent(String file, String conent) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            out.write(conent);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param name
     * @param toUpperCase 0是首字母小写 1是首字母大写
     * @return
     * @author cwq
     * @date 2017/9/12 下午3:42
     */
    public static String upFirstName(String name, Integer toUpperCase) {
        String s = null;
        if (name != null) {
//            s = name.toLowerCase();
            s = name;
            String first = "" + s.charAt(0);
            if (toUpperCase == 1) {
                first = first.toUpperCase();
            }
            if (toUpperCase == 0) {
                first = first.toLowerCase();
            }
            s = first + s.substring(1, s.length());
        }
        return s;
    }

    /**
     * @param name
     * @return
     * @author cwq
     * @date 2017/9/12 下午3:43
     * 驼峰式
     */
    public static String camelCase(String name) {
        StringBuffer stringBuffer = new StringBuffer();
        for (String t : name.split("_")) {
            stringBuffer.append(upFirstName(t, 1));
        }
        return upFirstName(stringBuffer.toString(), 0);
    }

    public static DataSource getDataSource() {
        //加载配置文件
        String url = PropertyUtil.getGrosseValue("db", "url");//获取数据库url
        String username = PropertyUtil.getGrosseValue("db", "username");//获取用户名字
        String password = PropertyUtil.getGrosseValue("db", "password");//密码
        //创建c3p0连接
        C3p0Plugin c3p0Plugin = new C3p0Plugin(url, username, password);//连接池
        c3p0Plugin.start();
        return c3p0Plugin.getDataSource();
    }

}