首页 > 编程语言 >java代码生成器(controller,service,mapper)

java代码生成器(controller,service,mapper)

时间:2024-10-18 23:09:45浏览次数:5  
标签:代码生成 java String tableName className controller import sb append

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

标签:代码生成,java,String,tableName,className,controller,import,sb,append
From: https://www.cnblogs.com/cyqf/p/18475213

相关文章

  • java Nodejs python php微信小程序的校园跑腿系统628
    目录项目介绍具体实现截图技术介绍HBuilderX协同过滤算法java类核心代码部分展示其他springboot项目推荐详细视频演示源码获取项目介绍伴随着社会以及科学技术的发展,小程序已经渗透在人们的身边,小程序慢慢的变成了人们的生活必不可少的一部分,紧接着网络飞速的发展,小......
  • IoT平台软件:Google Cloud IoT二次开发_JavaSDK使用指南
    JavaSDK使用指南1.环境准备在开始使用GoogleCloudIoT的JavaSDK之前,需要确保您的开发环境已经配置好相关的依赖和工具。以下是环境准备的步骤:1.1安装Java确保您的系统中安装了最新版本的Java开发工具包(JDK)。您可以通过以下命令检查Java版本:java-vers......
  • Java 中的访问权限
    文章目录前言一、Java中的四种访问权限级别1.public(公共访问权限):2.protected(受保护访问权限):3.默认访问权限(也称为包访问权限或友好访问权限):4.private(私有访问权限):二、访问权限的重要性总结前言在Java编程中,访问权限的控制是非常重要的一部分,它决定了类、方法......
  • 【Java SE 】类和对象详解
     ......
  • JavaWeb基于ssm的校园一卡通密钥管理系统(001)
    获取源码请滑到最底部访问官网项目配套调试视频和相对应的软件安装包1、项目描述具体请看视频演示2、项目开发工具开发工具:Idea或Eclipse数据库:MysqlJar包仓库:Maven前端框架:Vue2后端框架:SSM3、项目图片4、演示视频JavaWeb基于ssm的校园一卡通密钥管理系统(001)......
  • (附论文)JavaWeb基于ssm的爱尚美家家具购物网站系统(002)
    获取源码请滑到最底部访问官网项目配套调试视频和相对应的软件安装包1、项目描述具体请看视频演示2、项目开发工具开发工具:Idea或Eclipse数据库:MysqlJar包仓库:Maven前端框架:JSP后端框架:SSM3、项目图片4、演示视频(附论文)JavaWeb基于ssm的爱尚美家家具购物网站......
  • java_day16_IO、序列化
    一、IO流IO流划分IO流【输入输出流】:按照流向划分:输入流:外部数据->java程序输出流:java程序->外部数据按照数据类型划分【根据使用记事本打开是否能够看懂来决定】字节流【万能流】:字节输入流:InputStream【抽象类】-......
  • (附论文)JavaWeb基于ssm的高校毕业设计信息管理系统(054)
    获取源码请滑到最底部访问官网项目配套调试视频和相对应的软件安装包1、项目描述具体请看视频演示2、项目开发工具开发工具:Idea或Eclipse数据库:MysqlJar包仓库:Maven前端框架:Vue2后端框架:SSM3、项目图片4、演示视频(附论文)JavaWeb基于ssm的高校毕业设计信息管理......
  • 计算机毕业设计 | java swing 销售管理系统(附源码)
    1,概述1.1选题背景近几年来,传统商业与电商似乎是水火不容,大有不是你死便是我活的劲头。一直以来舆论都是一边倒的电商将迅速取代传统零售的论调,然而几年过去,电商的发展确实值得侧目,但传统商业虽然受到不小的影响,也依然顽强地挺立。事实上,就零售市场总规模而言,仍然是实体......
  • Java方法使用的细节
    在Java中,方法是一段可重用的逻辑代码块,用于执行特定的任务。以下是关于Java方法使用的一些细节:方法声明:方法应该先声明,再调用。方法的声明包括方法名、参数列表、返回类型和方法体。方法名应该以小写字母开头,并采用驼峰命名法。参数列表包括参数的类型和名称,多个参数之间用逗......