代码生成工具2 ——根据表名生成代码 备份

 1 解析表结构

package com.sourceJava.build;

import com.sourceJava.bean.Constants;
import com.sourceJava.bean.FieldInfo;
import com.sourceJava.bean.TableInfo;
import com.sourceJava.utils.MyStringUtils;
import com.sourceJava.utils.PropertiesUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;


import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
    构建表
 */
public class BuildTable {
    private static Connection conn = null;
    //查询表的状态,包括表名称、表备注等信息
    private static String SQL_SHOW_TABLE_STATUS = "show table status";
    //根据表名查询字段信息
    private static String SQL_SHOW_TABLE_FIELDS = "SHOW FULL FIELDS FROM %s";
    //根据表明查询索引信息
    private static String SQL_SHOW_TABLE_INDEX = "SHOW INDEX FROM %s";
    //加载数据库连接信息
    static {
        String driverName = PropertiesUtils.getValue("db.driver.name");
        String url = PropertiesUtils.getValue("db.url");
        String user = PropertiesUtils.getValue("db.username");
        String password = PropertiesUtils.getValue("db.password");
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url,user,password);
        }catch (Exception e){
            System.out.println("数据库连接失败" + e);
        }
    }

    //获取所有的表
    public static List<TableInfo> getTables(){
        PreparedStatement ps = null;
        ResultSet tableResult = null;
        List<TableInfo> tableInfoList = new ArrayList();
        try {
            ps = conn.prepareStatement(SQL_SHOW_TABLE_STATUS);
            tableResult = ps.executeQuery();
            while(tableResult.next()){
                String tableName = tableResult.getString("name");
                String comment = tableResult.getString("comment");
                TableInfo tableInfo = new TableInfo();
                String beanName = tableName;
                if(Constants.IGNORE_TABLE_PERFIX){
                    beanName = tableName.substring(beanName.indexOf("_") + 1);
                    //System.out.println(beanName);
                    beanName = caseName(beanName, true);
                    //System.out.println(beanName);
                }
                tableInfo.setBeanName(beanName);
                tableInfo.setTableName(tableName);
                tableInfo.setComment(comment);
                tableInfo.setBeanParamName(beanName + caseName(Constants.SUFFIX_BEAN_PARAM,true));
                List<FieldInfo> fieldInfos = readFieldInfo(tableInfo);
                tableInfoList.add(tableInfo);
                getKeyIndexInfo(tableInfo);
                //System.out.println("table:" + tableInfo.toString());
            }
        }catch (Exception e){
            System.out.println("读取表失败"+e);
        }finally {
            if(tableResult != null){
                try {
                    tableResult.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return tableInfoList;
    }

    //获取表里的字段信息
    private static List<FieldInfo> readFieldInfo(TableInfo tableInfo){

        PreparedStatement ps = null;
        ResultSet fieldResult = null;
        List<FieldInfo> fieldInfos = new ArrayList();
        try {
            ps = conn.prepareStatement(String.format(SQL_SHOW_TABLE_FIELDS,tableInfo.getTableName()));
            fieldResult = ps.executeQuery();
            while(fieldResult.next()){
                FieldInfo fieldInfo = new FieldInfo();
                fieldInfo.setFieldName(fieldResult.getString("field"));
                fieldInfo.setPropertyName(caseName(fieldResult.getString("field"),false));
                fieldInfo.setComment(caseName(fieldResult.getString("comment"),false));
                if(StringUtils.isNotEmpty(fieldResult.getString("Extra") )&& fieldResult.getString("Extra").equals("auto_increment")){
                    fieldInfo.setAutoIncrement(true);
                }else{
                    fieldInfo.setAutoIncrement(false);
                }
                String type = fieldResult.getString("type");
                if(type.indexOf("(") > 0){
                    type = type.substring(0,type.indexOf("("));
                }
                fieldInfo.setSqlType(caseName(type,false));
                fieldInfo.setJavaType(caseJavaType(type));
                fieldInfos.add(fieldInfo);

                if(ArrayUtils.contains(Constants.SQL_DATE_TIME_TYPE,type)){
                    tableInfo.setHaveDateTime(true);
                }
                if(ArrayUtils.contains(Constants.SQL_DATE_TYPE,type)){
                    tableInfo.setHaveDate(true);
                }
                if(ArrayUtils.contains(Constants.SQL_DECIMAL_TYPE,type)){
                    tableInfo.setHaveBigDecimal(true);
                }
            }
            tableInfo.setFieldInfoList(fieldInfos);
        }catch (Exception e){
            System.out.println("读取表失败"+e);
        }finally {
            if(fieldResult != null){
                try {
                    fieldResult.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

        }
        return fieldInfos;
    }

    //获取索引信息
    private static List<FieldInfo> getKeyIndexInfo(TableInfo tableInfo){

        PreparedStatement ps = null;
        ResultSet keysIndexResult = null;
        List<FieldInfo> tableInfoList = new ArrayList();
        try {
            Map<String,FieldInfo> map = new HashMap();
            for(FieldInfo fieldInfo:tableInfo.getFieldInfoList()){
                map.put(fieldInfo.getFieldName(),fieldInfo);
            }
            ps = conn.prepareStatement(String.format(SQL_SHOW_TABLE_INDEX,tableInfo.getTableName()));
            keysIndexResult = ps.executeQuery();
            while(keysIndexResult.next()){
                String keyName = keysIndexResult.getString("key_name");
                Integer nonUnique = keysIndexResult.getInt("non_unique");
                String columnName = keysIndexResult.getString("column_name");
                if(nonUnique == 1){
                    continue;
                }
                List<FieldInfo> keyFieldList = tableInfo.getKeyIndexMap().get(keyName);
                if(null == keyFieldList){
                    keyFieldList = new ArrayList();
                    tableInfo.getKeyIndexMap().put(keyName,keyFieldList);
                }
                keyFieldList.add(map.get(columnName));

            }
        }catch (Exception e){
            System.out.println("读取索引失败"+e);
        }finally {
            if(keysIndexResult != null){
                try {
                    keysIndexResult.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

        }
        return tableInfoList;
    }

    //表字段名转换成对应的Java字段名
    private static String caseName(String field,Boolean flag){
        StringBuilder sb = new StringBuilder();
        String[] fields = field.split("_");
        sb.append(flag? MyStringUtils.upCaseFirstLetter(fields[0]):fields[0]);
        for (int i = 1,len = fields.length; i < len; i++) {
            sb.append(MyStringUtils.upCaseFirstLetter(fields[i]));
        }
        return sb.toString();
    }

    //表字段类型转换成对应的Java字段类型
    private static String caseJavaType(String type){
        if(ArrayUtils.contains(Constants.SQL_INTEGER_TYPE,type)){
            return "Integer";
        }else if(ArrayUtils.contains(Constants.SQL_LONG_TYPE,type)){
            return "Long";
        }else if(ArrayUtils.contains(Constants.SQL_STRING_TYPE,type)){
            return "String";
        }else if(ArrayUtils.contains(Constants.SQL_DATE_TIME_TYPE,type)
                    || ArrayUtils.contains(Constants.SQL_DATE_TYPE,type)){
            return "Date";
        }else if(ArrayUtils.contains(Constants.SQL_DECIMAL_TYPE,type)){
            return "BigDecimal";
        }else {
            throw new RuntimeException("无法识别的类型: " + type );
        }
    }

    public static void main(String[] args) {
        BuildTable.getTables();
    }

}

2 解析备注

import com.sourceJava.utils.DateUtils;

import java.io.BufferedWriter;
import java.io.IOException;
import java.util.Date;

/**
 * 生成注释
 * @create 2024-04-30 23:19
 */
public class BuildComment {
    //类注释
    public static void createClassComment(BufferedWriter bufferedWriter,String classComment) throws Exception{
        bufferedWriter.write("/**");
        bufferedWriter.newLine();
        bufferedWriter.write("  @Description:" + classComment);
        bufferedWriter.newLine();
        bufferedWriter.write(" * Date:" + DateUtils.dateParseToString(DateUtils._YYYY_MM_DD,new Date()));
        bufferedWriter.newLine();
        bufferedWriter.write(" */");
        bufferedWriter.newLine();
    }
    //字段注释
    public static void createFieldComment(BufferedWriter bufferedWriter,String fieldComment) throws IOException {
        bufferedWriter.write(" \t/**");
        bufferedWriter.newLine();
        bufferedWriter.write(" \t * " + (fieldComment == null ? "":fieldComment));
        bufferedWriter.newLine();
        bufferedWriter.write(" \t*/");
        bufferedWriter.newLine();


    }

    //方法注释
    public static void createMethodComment(BufferedWriter bufferedWriter){

    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

geminigoth

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值