当前位置: 首页 > article >正文

mysql表逆向实体类

mysql表逆向实体类

目标框架springboot,mybatisplus

package com.wql.repackage;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class EntityClassGenerator {

    // todo 需要配置
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 3306;
    // todo 需要配置
    private static final String DATABASE = "数据库名称";
    // todo 需要配置
    private static final String USER = "用户名";
    // todo 需要配置
    private static final String PASSWORD = "密码";
    // todo 需要配置
    private static final String OUTPUTDIR = "C:\\Users\\Admin\\Desktop";

    private static final List<String> TABLE_NAMES = new ArrayList<>();

    private static final List<String> CLASS_CONTENTS = new ArrayList<>();

    private static final String URL = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DATABASE;


    // todo 需要配置
    // 是否增加mybatisplus注解
    private static final Boolean IS_ADD_MYBATISPLUS_ANNOTATION = true;
    private static final List<String> INSERT_FIELD_FILL_COLUMN_NAMES = new ArrayList<>();
    private static final List<String> INSERT_UPDATE_FIELD_FILL_COLUMN_NAMES = new ArrayList<>();

    // todo 需要配置
    // 是否逻辑删除
    private static final Boolean IS_LOGIC_DELETE = true;
    // todo 需要配置
    // 逻辑删除字段
    private static final String LOGIC_DELETE_COLUMN_NAME = "delete_flag";

    static{
        // 表
        TABLE_NAMES.add("i18n_module");
        TABLE_NAMES.add("i18n_keyword");
        // 表统一注释
        CLASS_CONTENTS.add("@author: 作者名称");
        CLASS_CONTENTS.add("@date: " + LocalDateTime.now());

        // 需要insert注解的字段
        INSERT_FIELD_FILL_COLUMN_NAMES.add("create_time");
        INSERT_FIELD_FILL_COLUMN_NAMES.add("create_user");
        // 需要update注解的字段
        INSERT_UPDATE_FIELD_FILL_COLUMN_NAMES.add("update_time");
        INSERT_UPDATE_FIELD_FILL_COLUMN_NAMES.add("update_user");

    }


    public static void main(String[] args) {

        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

            try {
                for (String tableName : TABLE_NAMES) {
                    generateEntityForTable(conn,CLASS_CONTENTS,tableName, OUTPUTDIR);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // 打印结束
            System.out.println("Entity class generated successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void generateEntityForTable(Connection conn, List<String> classContents,String tableName, String outputDir) throws SQLException, IOException {
        System.out.println("=========================>>表"+tableName+"=========");
        String className = toCamelCaseTableName(tableName);
        DatabaseMetaData metaData = conn.getMetaData();

        StringBuilder sb = new StringBuilder();
        sb.append("package com.example;\n\n");

        if (IS_ADD_MYBATISPLUS_ANNOTATION) {
            sb.append("import com.baomidou.mybatisplus.annotation.*;\n");
        }
        sb.append("import com.fasterxml.jackson.annotation.JsonFormat;\n");
        sb.append("import lombok.Data;\n\n");

        // 获取表的comment
        String classComment = generateClassComment(classContents);
        sb.append(classComment);

        sb.append("@Data\n");

        // 判断是否需要添加mybatisplus注解
        if(IS_ADD_MYBATISPLUS_ANNOTATION){
            sb.append("@TableName(\""+tableName+"\")\n");
        }


        sb.append("public class ").append(className).append(" {\n");

        String primaryKeyColumnName = "";
        ResultSet primaryKeys = metaData.getPrimaryKeys(DATABASE, null, tableName);
        if (primaryKeys.next()) {
            primaryKeyColumnName = primaryKeys.getString("COLUMN_NAME");
        }

        ResultSet columns = metaData.getColumns(null, null, tableName, null);

        while (columns.next()) {
            String columnName = columns.getString("COLUMN_NAME");
            String columnType = columns.getString("TYPE_NAME");
            String javaColumnName = toCamelCaseColumnName(columnName);
            System.out.println(columnName+"->DB字段类型:"+columnType+"");

            String comment = columns.getString("REMARKS");
            sb.append("    /** ").append(comment).append(" */\n");

            // 判断是否添加mybatisplus注解,并且判断是否主键,如果是主键,就添加
            // @TableId(type = IdType.ASSIGN_ID)
            // @JsonFormat(shape = JsonFormat.Shape.STRING)
            if(IS_ADD_MYBATISPLUS_ANNOTATION && primaryKeyColumnName.equalsIgnoreCase(columnName)){
                sb.append("    @TableId(type = IdType.ASSIGN_ID)\n");
                sb.append("    @JsonFormat(shape = JsonFormat.Shape.STRING)\n");
            }

            // 判断是否需要添加insert注解,并且判断是否是insert字段
            if(IS_ADD_MYBATISPLUS_ANNOTATION && INSERT_FIELD_FILL_COLUMN_NAMES.contains(columnName)){
                sb.append("    @TableField(fill = FieldFill.INSERT)\n");
            }
            // 判断是否需要添加update注解,并且判断是否是update字段
            if(IS_ADD_MYBATISPLUS_ANNOTATION && INSERT_UPDATE_FIELD_FILL_COLUMN_NAMES.contains(columnName)){
                sb.append("    @TableField(fill = FieldFill.INSERT_UPDATE)\n");
            }

            // 逻辑删除
            if(IS_ADD_MYBATISPLUS_ANNOTATION && IS_LOGIC_DELETE && LOGIC_DELETE_COLUMN_NAME.equalsIgnoreCase(columnName)){
                sb.append("    @TableLogic(value = \"0\", delval = \"1\")\n");
            }

            sb.append("    private ").append(mapSqlTypeToJava(columnType)).append(" ").append(javaColumnName).append(";\n\n");
        }

        sb.append("}\n");

        writeToFile(outputDir, className + ".java", sb.toString());

        System.out.println("=========================<<类"+className+"完毕!=====");
    }


    // 生成类注释
    private static String generateClassComment(List<String> classContents) {
        StringBuilder sb = new StringBuilder();
        sb.append("/** \n * \n");

        if(null != classContents){
            for (String classContent : classContents) {
                sb.append(" * ").append(classContent).append("\n");
            }
        }
        sb.append(" */\n");

        return sb.toString();
    }

    private static String mapSqlTypeToJava(String sqlType) {
        switch (sqlType.toUpperCase()) {
            case "DATE":
                return "LocalDate";
            case "DATETIME":
            case "TIMESTAMP":
                return "LocalDateTime";
            case "INT":
            case "BIT":
            case "TINYINT":
                return "Integer";
            case "BIGINT":
            case "BIGINT UNSIGNED":
                return "Long";
            case "VARCHAR":
            case "CHAR":
            case "TEXT":
                return "String";
            // todo 其他未处理的类型 在此处添加
            default:
                return "Object";
        }
    }


    private static String toCamelCaseTableName(String s) {
        if (s == null || s.isEmpty()) {
            return s;
        }
        String[] parts = s.split("_");
        StringBuilder camelCase = new StringBuilder();

        for (String part : parts) {
            if (!part.isEmpty()) {
                camelCase.append(part.substring(0, 1).toUpperCase()).append(part.substring(1).toLowerCase());
            }
        }

        return camelCase.append("DO").toString();
    }


    private static String toCamelCaseColumnName(String s) {
        if (s == null || s.isEmpty()) {
            return s;
        }
        String[] parts = s.split("_");
        StringBuilder camelCase = new StringBuilder();

        for (String part : parts) {
            if (!part.isEmpty()) {
                if (camelCase.length() == 0) {
                    camelCase.append(part.toLowerCase());
                } else {
                    camelCase.append(part.substring(0, 1).toUpperCase()).append(part.substring(1).toLowerCase());
                }
            }
        }

        return camelCase.toString();
    }


    private static void writeToFile(String dir, String fileName, String content) throws IOException {
        FileWriter writer = new FileWriter(dir + "/" + fileName);
        writer.write(content);
        writer.close();
    }
}
    


http://www.kler.cn/a/319520.html

相关文章:

  • git命令及原理
  • 如何在有限内存下对外部大文件进行排序
  • ReactPress:构建高效、灵活、可扩展的开源发布平台
  • 第四十三章 Vue之mapMutations简化mutations操作
  • FPGA高速设计之Aurora64B/66B的应用与不足的修正
  • Vue 2 —Vue Router 页面导航和参数传递
  • Linux 基础IO 2
  • 网络原理之IP协议(网络层)
  • java线程Thread的组名是main就是在主线程吗?
  • LeetCode 每周算法 6(图论、回溯)
  • react:React Hook函数
  • MySQL篇(存储引擎)(持续更新迭代)
  • 杂牌鼠标侧键设置
  • C++:AB5 点击消除
  • 基于大数据的电子产品需求数据分析系统的设计与实现(Python Vue Flask Mysql)
  • 每日一题|2306. 公司命名|哈希映射、集合运算
  • FastAPI挂载静态资源
  • 单词记忆的化境:用思想的流水去淹没坚硬的石块
  • 【网络安全】网络基础第一阶段——第四节:网络协议基础---- VRRP与网络架构设计
  • 三种springboot启动时加载方式
  • 使用Renesas R7FA8D1BH (Cortex®-M85)和微信小程序App数据传输
  • 黑盒测试 | 挖掘.NET程序中的反序列化漏洞
  • 统信服务器操作系统【d版系统上Ansible工具】配置方法
  • MySQL:表的约束
  • 2.Seata 1.5.2 集成Springcloud-alibaba
  • 【算法】贪心+堆排序实现大根堆及标准库容器类的融合使用