jfinal根据表创建get set 方法

子车鸿才
2023-12-01

1.引入包 pom.xml

  <!--数据库链接的包-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>mchange-commons-java</artifactId>
            <version>0.2.12</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!--freemarker 生成模版工具-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.16</version>
        </dependency>

2.freemarker 模版
Model.ftl

package ${package};
import java.util.Date;
import com.se.BasicModel;
import com.se.ext.plugin.tablebind.TableBind;
@SuppressWarnings("serial")
@TableBind(pkName = "${pkName}")
public class ${modelName} extends BasicModel <${modelName}> {
    public static final ${modelName} dao = new ${modelName}();
    <#list tableColumns as columns>

        <#if columns[2]!="">
        //${columns[2]}
        </#if>
    public ${columns[1]} get${columns[5]} (){
        return this.${columns[3]}("${columns[0]}");
    }

    </#list>
    <#list tableColumns as columns>

    public ${modelName} set${columns[5]} (${columns[1]} ${columns[4]}) {
        this.set("${columns[0]}", ${columns[4]});
        return this;
    }

    </#list>
}

3.编码转换
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", "BigInteger"), 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", "getBigInteger"), 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;
    }
}

4.程序
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.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]);
//        }
        createModel("b_activity_teacher");

    }

    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();
    }

}
 类似资料: