rk
8 小时以前 56fcde8c93a1a10bc50fac775e370a2db57f520e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package com.doumee.core.utils;
 
 
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
 
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.*;
import java.util.Date;
import java.util.*;
 
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
    public static  String packName ="com.doumee";
    // 设置输出目录
    public static String rootFileDir = "D:/code/idea/initCode/";
    public static  String outputDirEntity =rootFileDir+"src/main/java/com/doumee/dao/business/model/"; // 输出的代码文件夹路径
    public static  String outputDirMapper = rootFileDir+"src/main/java/com/doumee/dao/business/"; // 输出的代码文件夹路径
    public static  String outputDirService =rootFileDir+"src/main/java/com/doumee/service/business/"; // 输出的代码文件夹路径
    public static  String outputDirServiceImpl = rootFileDir+"src/main/java/com/doumee/service/business/impl/"; // 输出的代码文件夹路径
    public static  String outputDirController =rootFileDir+"src/main/java/com/doumee/api/business/"; // 输出的代码文件夹路径
    public static  String outputDirDb =rootFileDir+"db/"; // 输出的代码文件夹路径
    public static void main(String[] args) {
        // 配置数据库连接
        String url = "jdbc:mysql://192.168.0.211:3306/dmmall_full";
        String username = "root";
        String password = "Doumee@168";
        String database = "dmmall_full";
        List<String> tables = new ArrayList<>();
        tables.add("member");
        tables.add("labels");
        tables.add("goods");
        tables.add("goodsorder");
        tables.add("integral");
 
        for(String tableName : tables){
            // 获取表信息并生成代码
            try {
                System.out.println(tableName+"===================生成开始===================");
                Map<String, Object> tableInfo = getTableInfo(url, username, password, database, tableName);
                generateCode(tableInfo);
                System.out.println(tableName+"===================生成结束===================");
            }catch (Exception e){
                System.err.println(tableName+"===================生成异常==================="+e.getMessage());
            }
        }
 
    }
 
 
    public static Map<String, Object> getTableInfo(String url, String username, String password, String database, String tableName) {
        Map<String, Object> map = new HashMap<>();
        try (Connection conn = DriverManager.getConnection(url, username, password)) {
            // 查询表注释
            String tableQuery = "SELECT table_comment FROM information_schema.tables WHERE table_schema = ? AND table_name = ?";
            try (PreparedStatement ps = conn.prepareStatement(tableQuery)) {
                ps.setString(1, database);
                ps.setString(2, tableName);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    map.put("tableComment", rs.getString("table_comment"));
                }
            }
            // 查询字段信息 auto_increment
            String columnQuery = "SELECT extra,column_name, column_type, column_comment FROM information_schema.columns WHERE table_schema = ? AND table_name = ? order by ordinal_position";
            List<Map<String, String>> columns = new ArrayList<>();
            try (PreparedStatement ps = conn.prepareStatement(columnQuery)) {
                ps.setString(1, database);
                ps.setString(2, tableName);
                ResultSet rs = ps.executeQuery();
                int index = 1;
                while (rs.next()) {
                    String javaName = toCamelCase(rs.getString("column_name"));
                    String getJavaName = javaName.substring(0,1).toUpperCase()+javaName.substring(1);
                    Map<String, String> columnInfo = new HashMap<>();
                    if(rs.getString("extra") !=null
                            && rs.getString("extra").contains("auto_increment")){
                        //如果是自增长
                        columnInfo.put("auto","1");  // 转换为 Java 变量名
                    }else{
                        columnInfo.put("auto","0");  // 转换为 Java 变量名
                    }
                    columnInfo.put("index",index++ +"");
                    columnInfo.put("columnName", rs.getString("column_name"));
                    columnInfo.put("javaName",javaName);  // 转换为 Java 变量名
                    columnInfo.put("getJavaName",getJavaName);  // 转换为 Java 变量名
                    columnInfo.put("javaType", sqlTypeToJavaType(rs.getString("column_type")));  // 转换为 Java 类型
                    columnInfo.put("comment", rs.getString("column_comment"));
                    columns.add(columnInfo);
                }
            }
            map.put("columns", columns);
            map.put("tableName", tableName);
            map.put("entityName", toCamelCase(tableName));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return map;
    }
 
    private static String sqlTypeToJavaType(String sqlType) {
        sqlType = sqlType.toLowerCase();
        if (sqlType.contains("int")) {
            return "Integer";
        } else if (sqlType.contains("bigint")) {
            return "Long";
        } else if (sqlType.contains("char") || sqlType.contains("text") || sqlType.contains("varchar")) {
            return "String";
        } else if (sqlType.contains("datetime") || sqlType.contains("timestamp")) {
            return "Date";
        } else if (sqlType.contains("date")) {
            return "Date";
        } else if (sqlType.contains("decimal") || sqlType.contains("double")) {
            return "BigDecimal";
        } else {
            return "String";
        }
    }
 
    private static String toCamelCase(String name) {
        StringBuilder result = new StringBuilder();
        String[] parts = name.split("_");
        for (int i = 0; i < parts.length; i++) {
            if (i == 0) {
                result.append(parts[i].toLowerCase());
            } else {
                result.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1).toLowerCase());
            }
        }
        return result.toString();
    }
    private static void generateCode(Map<String, Object> tableInfo) {
        // 读取表信息
        String entityName = (String) tableInfo.get("entityName");
        String tableName = (String) tableInfo.get("tableName");
        String tableComment = (String) tableInfo.get("tableComment");
        List<Map<String, String>> columns = (List<Map<String, String>>) tableInfo.get("columns");
 
 
        // 设置 Velocity 配置
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.init();
        // 配置模板目录
        String baseName = entityName.substring(0, 1).toUpperCase() + entityName.substring(1);
        // 创建 Velocity 上下文
        Map<String,String> pack = new HashMap<>();
        pack.put("Base",packName);
        pack.put("Entity",packName+".dao.business.model");
        pack.put("Controller",packName+".api.business");
        pack.put("Mapper",packName+".dao.business");
        pack.put("Service",packName+".service.business");
        pack.put("ServiceImpl",packName+".service.business.impl");
        VelocityContext context = new VelocityContext();
        context.put("package",pack); // 设置包路径
        context.put("entityName", baseName);
        context.put("entityNameLower", entityName);
        context.put("entityNameLowerFull", entityName.toLowerCase());
        context.put("tableName", tableName);
        context.put("tableComment", tableComment);
        context.put("columns", columns);
        context.put("nowDate", DateUtil.getPlusTime2(new Date()));
 
        // 生成 Entity 文件
        generateFile(velocityEngine, context,  "entity.vm", baseName, outputDirEntity  , ".java");
 
        // 生成 Mapper 文件
        generateFile(velocityEngine, context,  "mapper.vm",  baseName, outputDirMapper , "Mapper.java");
 
        // 生成 Service 接口文件
        generateFile(velocityEngine, context,  "service.vm",  baseName, outputDirService  , "Service.java");
 
        // 生成 ServiceImpl 文件
        generateFile(velocityEngine, context,  "serviceImpl.vm",  baseName, outputDirServiceImpl + "" , "ServiceImpl.java");
 
        // 生成 Controller 文件
        generateFile(velocityEngine, context,  "controller.vm",  baseName, outputDirController  , "Controller.java");
        generateFile(velocityEngine, context,  "db.vm",  baseName, outputDirDb  , "Permissions.sql");
    }
 
    private static void generateFile(VelocityEngine velocityEngine, VelocityContext context,  String templateName, String baseName,String outputFilePath,String endName)  {
        // 获取模板
        File file = new File(outputFilePath);
        if(!file.isDirectory()){
            file.mkdirs();
        }
        System.out.println(file.isFile());
        Template template = velocityEngine.getTemplate(  "templates/"+templateName);
 
        // 创建文件输出流
        try{
 
            System.out.println(outputFilePath+baseName+endName+"===================生成开始===================");
            File f = new File(outputFilePath+baseName+endName);
            if(f.isFile()){
                f.delete();
            }
            f.createNewFile();
            // 将上下文数据渲染到模板中
            FileWriter writer = new FileWriter(outputFilePath+baseName+endName);
            template.merge(context, writer);
            writer.flush();
            writer.close();
            System.out.println(outputFilePath+baseName+endName+"===================生成结束===================");
        } catch (IOException e) {
            System.err.println(outputFilePath+baseName+endName+"===================生成异常===================");
            e.printStackTrace();
        }
    }
 
}