遇到百张数据表也不怕,Java自动生成实体、Controller

2020-03-11  本文已影响0人  秦胜飞_3838

一、说明

该工具类实现以下功能:
1、简单的controller方法
2、自动生成Dao类
2、自动生成Service类
2、自动生成ServiceImpl类

二、连接数据库


    // 数据库配置信息
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&autoReconnect=true";
    private static final String NAME = "root";
    private static final String PASS = "123456";
    private static final String DRIVER = "com.mysql.jdbc.Driver";

第二步:其他相关配置

 //表名
    private String tableName;
    //列名数组
    private String[] colNames;
    //列名类型数组
    private String[] colTypes;
    //列名大小数组
    private int[] colSizes;
    //列名注释
    private Map colNamesComment = new HashMap();
    //是否需要导入包java.util.*
    private boolean needUtil = false;
    //是否需要导入包java.sql.*
    private boolean needSql = false;
    //是否需要导入包java.math.BigDecimal
    private boolean needBigDecimal = false;
    //是否创建EntityHelper
    private boolean needEntityHelper = true;
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final String SQL = "SELECT * FROM ";// 数据库操作
    
    
    //指定实体生成所在包的路径
    private static String basePath = new File("").getAbsolutePath();
    //指定包名
    private static String packageEntityOutPath = "com.qinshengfei.system.entity";

    //指定包名
    private static String packageControllerOutPath = "com.qinshengfei.system.controller";

    private static String packageDaoOutPath = "com.qinshengfei.system.dao";

    private static String packageServiceOutPath = "com.qinshengfei.system.service";
    private static String packageServiceimpleOutPath = "com.qinshengfei.system.service.impl";

    //作者名字
    private String authorName = "qinshengfei";
    //指定需要生成的表的表名,全部生成设置为null
    private String[] generateTables = null;
    //主键
    private static String pk;

第三步:main方法编写


    public static void main(String[] args) {
        MySQLGeneratorEntityUtil instance = new MySQLGeneratorEntityUtil();
        //instance.basePath=""; //指定生成的位置,默认是当前工程
        try {
            instance.generate();
            System.out.println("generate Entity to classes successful!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

第四步:了解instance.generate()方法

 /**
     * @description 生成方法
     */
    private void generate() throws Exception {
        //与数据库的连接
        Connection con;
        PreparedStatement pStemt = null;
        Class.forName(DRIVER);
        con = DriverManager.getConnection(URL, NAME, PASS);
        System.out.println("connect database success..."+con);
        //获取数据库的元数据
        DatabaseMetaData db = con.getMetaData();
        //是否有指定生成表,有指定则直接用指定表,没有则全表生成
        List<String> tableNames = new ArrayList<>();
        if (generateTables == null) {
            //从元数据中获取到所有的表名
            //ResultSet rs = db.getTables(null, null, null, new String[] { "TABLE" });
            ResultSet rsTables = db.getTables(null, null, "%", null);
            while (rsTables .next()) {
                String tablename = rsTables.getString(3) ;
                if (tablename.contains("bc_")){
                    tableNames.add(rsTables.getString(3));
                }
            }

           // while (rs.next()) tableNames.add(rs.getString(3));
        } else {
            for (String tableName : generateTables) tableNames.add(tableName);
        }
        if(needEntityHelper) {
            EntityHelper();
        }
        String tableSql;
        PrintWriter pw = null;
        for (int j = 0; j < tableNames.size(); j++) {

            tableName = tableNames.get(j);
            tableSql = SQL + tableName;
            pStemt = con.prepareStatement(tableSql);
            ResultSetMetaData rsmd = pStemt.getMetaData();
            ResultSet rsk = con.getMetaData().getPrimaryKeys(con.getCatalog().toLowerCase(), null, tableName);
            if (rsk.next()) {
                String primaryKey = rsk.getString("COLUMN_NAME");
                pk=primaryKey;
            }
            int size = rsmd.getColumnCount();
            colNames = new String[size];
            colTypes = new String[size];
            colSizes = new int[size];
            //获取所需的信息
            for (int i = 0; i < size; i++) {
                colNames[i] = rsmd.getColumnName(i + 1);
                colTypes[i] = rsmd.getColumnTypeName(i + 1);
                if (colTypes[i].equalsIgnoreCase("datetime"))
                    needUtil = true;
                if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text"))
                    needSql = true;
                colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
            }
            //获取字段注释
            ResultSet rsComment = pStemt.executeQuery("show full columns from " + tableName);
            while (rsComment.next()) {
                colNamesComment.put(rsComment.getString("Field"), rsComment.getString("Comment"));
            }

            //输出生成文件
            String content = makeEntity();
            String dirName = MySQLGeneratorEntityUtil.pkgEntityDirName();
            String javaPath = dirName + "/" + under2camel(tableName, true) + ".java";
            FileWriter fw = new FileWriter(javaPath);
            pw = new PrintWriter(fw);
            pw.println(content);
            pw.flush();

            ///controller
            String makeControllerContent = makeController();
            String dirControllerName = MySQLGeneratorEntityUtil.pkgControllerDirName();
            String javaCPath = dirControllerName + "/" + under2camel(tableName, true) + "Controller.java";
            FileWriter fwcontroller = new FileWriter(javaCPath);
            pw = new PrintWriter(fwcontroller);
            pw.println(makeControllerContent);
            pw.flush();
            ///dao

            String daoContent = makeDao();
            String dirDaoName = MySQLGeneratorEntityUtil.pkgDaoDirName();
            String javadaoPath = dirDaoName + "/" + under2camel(tableName, true) + "Dao.java";
            FileWriter fwdao = new FileWriter(javadaoPath);
            pw = new PrintWriter(fwdao);
            pw.println(daoContent);
            pw.flush();

            ///service
            String serviceContent = makeService();
            String dirServiceName = MySQLGeneratorEntityUtil.pkgDaoDirName();
            String javaServicePath = dirServiceName + "/" + under2camel(tableName, true) + "Service.java";
            FileWriter fwService = new FileWriter(javaServicePath);
            pw = new PrintWriter(fwService);
            pw.println(serviceContent);
            pw.flush();

            ///serviceImpl
            String serviceImplContent = makeServiceImpl();
            String javaServiceImplPath = dirName + "/service/impl/" + under2camel(tableName, true) + "ServiceImpl.java";
            FileWriter fwServiceimpl = new FileWriter(javaServiceImplPath);
            pw = new PrintWriter(fwServiceimpl);
            pw.println(serviceImplContent);
            pw.flush();



            System.out.println("create class 【" + tableName + "】");
        }
        if (pw != null)
            pw.close();
    }

第五步 了解entity的生成

所有自定义的Entity都是这编写。。。
 /**
     * @description 生成class的所有内容
     */
    private String makeEntity() {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + packageEntityOutPath + ";\r\n");
        sb.append("\r\n");
        // 判断是否导入工具包
        if (needUtil) {
            sb.append("import java.util.Date;\r\n");
        }
        if (needSql) {
            sb.append("import java.sql.*;\r\n");
        }

        for (int i = 0; i < colNames.length; i++) {
            String hasbd = sqlType2JavaType(colTypes[i]);
            if(hasbd =="BigDecimal" || "BigDecimal".equals(hasbd)) {needBigDecimal=true;}
        }
        if(needBigDecimal) {
            sb.append("import java.math.BigDecimal;\r\n");
        }
        // 注释部分
        sb.append("/**\r\n");
        sb.append(" * table name:  " + tableName + "\r\n");
        sb.append(" * author name: " + authorName + "\r\n");
        sb.append(" * create time: " + SDF.format(new Date()) + "\r\n");
        sb.append(" */ \r\n");
        // 实体部分
        String classExtends = "";
        if(needEntityHelper) {
            classExtends=" extends EntityHelper";
        }
        sb.append("public class " + under2camel(tableName, true) + classExtends + "{\r\n\r\n");

        processAllAttrs(sb);// 属性
        sb.append("\r\n");
        processConstructor(sb);//构造函数
        processAllMethod(sb);// get set方法
        processToString(sb);
        if(needEntityHelper) {
            processEntityHelper(sb,pk);
        }
        sb.append("}\r\n");
        return sb.toString();
    }

第六步:编写Dao层


    /**
     * @description 生成class的所有内容
     */
    private String makeDao() {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + packageDaoOutPath + ";\r\n");
        sb.append("import org.apache.ibatis.annotations.Insert;  \r\n");
        sb.append("import org.apache.ibatis.annotations.Update;  \r\n");
        sb.append("import org.springframework.stereotype.Component;  \r\n");
        sb.append("import com.qinshengfei.system.entity."+under2camel(tableName, true)+" ; \r\n");
        sb.append("import org.apache.ibatis.annotations.Select;\r\n");
        sb.append("import java.util.List;\r\n");

        sb.append("\r\n");
        // 判断是否导入工具包

        // 注释部分
        sb.append("/**\r\n");
        sb.append(" * table name:  " + tableName + "\r\n");
        sb.append(" * author name: " + authorName + "\r\n");
        sb.append(" * create time: " + SDF.format(new Date()) + "\r\n");
        sb.append(" */ \r\n");
        // 实体部分
        String classExtends = "";
        if(needEntityHelper) {
            classExtends=" ";
        }
        sb.append("@Component\n");

        sb.append("public interface " + under2camel(tableName, true) + "Dao" + "{\r\n\r\n");

        sb.append("\r\n");
        processDaoMethed(sb);
        sb.append("}\r\n");
        return sb.toString();
    }

第七步:编写Service


    /**
     * @description 生成class的所有内容
     */
    private String makeService() {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + packageServiceOutPath + ";\r\n");
        sb.append("\r\n");
        // 判断是否导入工具包
        sb.append("import com.qinshengfei.system.entity."+under2camel(tableName, true)+" ; \r\n");
        sb.append("import java.util.List;\r\n");
        // 注释部分
        sb.append("/**\r\n");
        sb.append(" * table name:  " + tableName + "\r\n");
        sb.append(" * author name: " + authorName + "\r\n");
        sb.append(" * create time: " + SDF.format(new Date()) + "\r\n");
        sb.append(" */ \r\n");
        // 实体部分
        String classExtends = "";
        if(needEntityHelper) {
            classExtends=" extends EntityHelper";
        }
        sb.append("public interface " + under2camel(tableName, true) + "Service" + "{\r\n\r\n");
        processServiceMethed(sb);
        sb.append("}\r\n");
        return sb.toString();
    }

第八:编写Service实现类


    /**
     * @description 生成class的所有内容
     */
    private String makeServiceImpl() {
        StringBuffer sb = new StringBuffer();
        sb.append("package " + packageServiceimpleOutPath + ";\r\n");
        sb.append("\r\n");
        // 判断是否导入工具包
        sb.append("import com.qinshengfei.system.entity."+under2camel(tableName, true)+" ; \r\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
        sb.append("import com.qinshengfei.system.service."+under2camel(tableName, true)+"Service ; \r\n");
        sb.append("import com.qinshengfei.system.dao."+under2camel(tableName, true)+"Dao ; \r\n");
        sb.append("import org.springframework.stereotype.Service;\r\n");
        sb.append("import java.util.List;\r\n");
        sb.append("import org.springframework.stereotype.Service;\r\n");
        // 注释部分
        sb.append("/**\r\n");
        sb.append(" * table name:  " + tableName + "\r\n");
        sb.append(" * author name: " + authorName + "\r\n");
        sb.append(" * create time: " + SDF.format(new Date()) + "\r\n");
        sb.append(" */ \r\n");
        // 实体部分
        String classExtends = "";
        //if(needEntityHelper) {
            classExtends=" implements "+under2camel(tableName, true) +"Service";
       // }
        sb.append("@Service\r\n");
        sb.append("public class " + under2camel(tableName, true) + "ServiceImpl  " +classExtends+  "{\r\n\r\n");
        processServiceImplMethed(sb);
        sb.append("}\r\n");
        return sb.toString();
    }

最后,因为还有一些工具方法,最完整代码参见:

https://gitee.com/Qinux/MySQLGeneratorEntityUtil

上一篇下一篇

猜你喜欢

热点阅读