java程式碼生成器(controller,service,mapper)

赤叶秋枫發表於2024-10-18
package com.cn.codeGenerator;
import java.awt.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CodeGenerator {

    private static final String URL = "jdbc:mysql://localhost:3306/my_test_project?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    private static final String BASE_PACKAGE = "com.cn";

    public static void main(String[] args) throws SQLException, IOException {

        String tableName = "test01";  // 這裡可以修改表名
        generateCode(tableName);
    }

    public static void generateCode(String tableName) throws SQLException, IOException {
        Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
        DatabaseMetaData metaData = connection.getMetaData();

        ResultSet resultSet = metaData.getColumns(null, null, tableName, null);
        List<Column> columns = new ArrayList<>();

        while (resultSet.next()) {
            String columnName = resultSet.getString("COLUMN_NAME");
            String dataType = resultSet.getString("TYPE_NAME");
            if (columns.contains(columnName)){
                break;
            }
            columns.add(new Column(columnName, mapJavaType(dataType)));
        }

        String primaryKey = getPrimaryKey(metaData, tableName);

        generateEntity(tableName, columns);
        generateMapper(tableName, columns);
        generateMapperXml(tableName, columns, primaryKey);
        generateService(tableName);
        generateServiceImpl(tableName);
        generateController(tableName);

        System.out.println("程式碼生成完成!");
    }

    private static String getPrimaryKey(DatabaseMetaData metaData, String tableName) throws SQLException {
        ResultSet pkResultSet = metaData.getPrimaryKeys(null, null, tableName);
        if (pkResultSet.next()) {
            return pkResultSet.getString("COLUMN_NAME");
        }
        return null;
    }

    private static String mapJavaType(String sqlType) {
        switch (sqlType.toLowerCase()) {
            case "varchar":
            case "char":
            case "text":
                return "String";
            case "int":
            case "integer":
                return "Integer";
            case "bigint":
                return "Long";
            case "datetime":
            case "timestamp":
                return "Date";
            default:
                return "Object"; // 根據需要新增更多對映
        }
    }

    private static void generateEntity(String tableName, List<Column> columns) throws IOException {
        String className = toCamelCase(tableName, true);
        StringBuilder sb = new StringBuilder();
        sb.append("package ").append(BASE_PACKAGE).append(".entity;\n\n");
        sb.append("import java.util.Date;\n");
        sb.append("public class ").append(className).append(" {\n");

        for (Column column : columns) {
            sb.append("\tprivate ").append(column.getJavaType()).append(" ").append(toCamelCase(column.getName(), false)).append(";\n");
        }
        sb.append("}\n");

        writeFile("entity", className + ".java", sb.toString());
    }

    private static void generateMapper(String tableName, List<Column> columns) throws IOException {
        String className = toCamelCase(tableName, true);
        StringBuilder sb = new StringBuilder();
        sb.append("package ").append(BASE_PACKAGE).append(".mapper;\n\n");
        sb.append("import ").append(BASE_PACKAGE).append(".entity.").append(className).append(";\n");
        sb.append("import org.apache.ibatis.annotations.Mapper;");
        sb.append("\n");
        sb.append("\n");
        sb.append("@Mapper\n");
        sb.append("public interface ").append(className).append("Mapper extends BaseMapper<"+className+">{\n");
        sb.append("}\n");

        writeFile("mapper", className + "Mapper.java", sb.toString());
    }

    private static void generateMapperXml(String tableName, List<Column> columns, String primaryKey) throws IOException {
        String className = toCamelCase(tableName, true);
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
        sb.append("<mapper namespace=\"").append(BASE_PACKAGE).append(".mapper.").append(className).append("Mapper\">\n");

        sb.append("</mapper>\n");

        writeFile("mapper/xml", className + "Mapper.xml", sb.toString());
    }

    private static void generateService(String tableName) throws IOException {
        String className = toCamelCase(tableName, true);
        StringBuilder sb = new StringBuilder();
        sb.append("package ").append(BASE_PACKAGE).append(".service;\n\n");
        sb.append("\n");
        sb.append("public interface ").append(className).append("Service  extends IService<"+className+">{\n");
        sb.append("}\n");

        writeFile("service", className + "Service.java", sb.toString());
    }

    private static void generateServiceImpl(String tableName) throws IOException {
        String className = toCamelCase(tableName, true);
        StringBuilder sb = new StringBuilder();
        sb.append("package ").append(BASE_PACKAGE).append(".service.impl;\n\n");
        sb.append("import ").append(BASE_PACKAGE).append(".entity.").append(className).append(";\n");
        sb.append("import ").append(BASE_PACKAGE).append(".mapper.").append(className).append("Mapper;\n");
        sb.append("import ").append(BASE_PACKAGE).append(".service.").append(className).append("Service;\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
        sb.append("import org.springframework.stereotype.Service;\n");

        sb.append("@Service\n");
        sb.append("public class ").append(className).append("ServiceImpl ").append("extends ServiceImpl<"+className+"Mapper,"+className+">")
                .append(" implements ").append(className).append("Service {\n");

        sb.append("\t@Autowired\n");
        sb.append("\tprivate ").append(className).append("Mapper ").append(toCamelCase(className, false)).append("Mapper;\n");

        sb.append("}\n");

        writeFile("service/impl", className + "ServiceImpl.java", sb.toString());
    }

    private static void generateController(String tableName) throws IOException {
        String className = toCamelCase(tableName, true);
        StringBuilder sb = new StringBuilder();
        sb.append("package ").append(BASE_PACKAGE).append(".controller;\n\n");
        sb.append("import ").append(BASE_PACKAGE).append(".entity.").append(className).append(";\n");
        sb.append("import ").append(BASE_PACKAGE).append(".service.").append(className).append("Service;\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
        sb.append("import org.springframework.web.bind.annotation.*;\n");
        sb.append("@RestController\n");
        sb.append("@RequestMapping(\"/").append(toCamelCase(tableName, false)).append("\")\n");
        sb.append("public class ").append(className).append("Controller {\n");
        sb.append("\t@Autowired\n");
        sb.append("\tprivate ").append(className).append("Service ").append(toCamelCase(className, false)).append("Service;\n");
        sb.append("}\n");

        writeFile("controller", className + "Controller.java", sb.toString());
    }

    private static void writeFile(String dir, String fileName, String content) throws IOException {
        String filePath = "output/" + dir;
        File folder = new File(filePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        FileWriter writer = new FileWriter(filePath + "/" + fileName);
        writer.write(content);
        // 開啟檔案所在的資料夾
        if ("controller".equals(dir)&&Desktop.isDesktopSupported()) {
            Desktop.getDesktop().open(folder.getParentFile());
        } else {
            System.out.println("桌面操作不支援");
        }
        writer.close();
    }

    private static String toCamelCase(String text, boolean capitalizeFirst) {
        StringBuilder result = new StringBuilder();
        boolean toUpperCase = capitalizeFirst;
        for (char c : text.toCharArray()) {
            if (c == '_') {
                toUpperCase = true;
            } else if (toUpperCase) {
                result.append(Character.toUpperCase(c));
                toUpperCase = false;
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }


    static class Column {
        private final String name;
        private final String javaType;

        public Column(String name, String javaType) {
            this.name = name;
            this.javaType = javaType;
        }

        public String getName() {
            return name;
        }

        public String getJavaType() {
            return javaType;
        }
    }
}

相關文章