jinlin
2024-01-23 52a302b11c08cbc564ff3931038ae57a305a95d6
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有,侵权必究!
 */
 
package com.zt.generator.utils;
 
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zt.common.exception.RenException;
import com.zt.generator.model.Column;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.texen.util.FileUtil;
 
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * 代码生成器 工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class GenUtils {
 
    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("template/Entity.java.vm");
        templates.add("template/Dao.java.vm");
        templates.add("template/Dao.xml.vm");
        templates.add("template/Service.java.vm");
        templates.add("template/Controller.java.vm");
        templates.add("template/Excel.java.vm");
        templates.add("template/index.vue.vm");
        templates.add("template/add-or-update.vue.vm");
        // templates.add("template/mysql.vm");
        return templates;
    }
 
    public static void generatorCode(String tableName, String isGenService, String className, String isPageFlag,
            String isExport, JSONArray columns, String packageName, String javaFilePath, String vueFilePath) {
        boolean hasBigDecimal = false, hasDate = false;
        // 列信息
        List<Column> columsList = new ArrayList<>();
        String filter = ",id,creator,updater,update_date,create_date,is_delete,tenant_id,company_id,dept_id,)";
        String createFilter = ",creator,create_date,tenant_id,company_id,dept_id,)";
        String updateFilter = ",updater,update_date,is_delete,)";
        int createCount = 0, updateCount = 0;
        Column pkColumn = null;
        for (int i = 0; i < columns.size(); i++) {
            JSONObject object = columns.getJSONObject(i);
 
            Column columnEntity = new Column();
            String columnName = object.getString("columnName");
            if ("id".equals(columnName.toLowerCase())) {
                continue;
            }
            if (createFilter.indexOf("," + columnName.toLowerCase() + ",") >= 0) {
                createCount++;
                continue;
            }
            if (updateFilter.indexOf("," + columnName.toLowerCase() + ",") >= 0) {
                updateCount++;
                continue;
            }
            columnEntity.setColumnName(columnName);
            columnEntity.setDataType(object.getString("typeName"));
            String comment = object.getString("remarks");
            if (StringUtils.isNotEmpty(comment)) {
                comment = comment.trim();
            }
            int index = comment.indexOf(" ");
            if (index > 0) {
                comment = comment.substring(0, index);
            }
            index = comment.indexOf("。");
            if (index > 0) {
                comment = comment.substring(0, index);
            }
            columnEntity.setComments(comment);
            columnEntity.setIsSelectColumn(object.getString("isSelectColumn"));
            columnEntity.setIsTableColumn(object.getString("isTableColumn"));
            columnEntity.setDictType(object.getString("dictType"));
            columnEntity.setOp(object.getString("op"));
 
            // 列名转换成Java属性名
            String attrName = columnToJava(columnEntity.getColumnName());
            columnEntity.setAttrName(StringUtils.uncapitalize(attrName));
 
            // 列的数据类型,转换成Java类型
            String attrType = map.get(columnEntity.getDataType());
            if (StringUtils.isBlank(attrType)) {
                attrType = "String";
            }
            columnEntity.setAttrType(attrType);
            if (!hasBigDecimal && attrType.equals("BigDecimal")) {
                hasBigDecimal = true;
            }
            if (!hasDate && attrType.equals("Date")) {
                hasDate = true;
            }
            // 是否主键
            if ("Y".equalsIgnoreCase(object.getString("isKey"))) {
                if (pkColumn != null) {
                    throw new RenException("请不要设置联合主键");
                }
                pkColumn = columnEntity;
            }
            columsList.add(columnEntity);
        }
 
        // 设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
 
        // 封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("tableName", tableName);// 表名@TableName("${tableName}")
        map.put("comments", tableName);
        if (createCount < 5) {
            throw new RenException("数据库字段缺失,请按照规范");
        } else if (updateCount == 3) {
            map.put("entityType", "BusiEntity");
        } else {
            map.put("entityType", "BusiLogEntity");
        }
        map.put("pk", pkColumn);
        map.put("package", packageName);
        map.put("className", className);  //实体类名字
        // private ${className}Service ${classBean}Service;
        map.put("classBean", StringUtils.uncapitalize(className));  //实体实例名字
        // model bean的名称insert(@RequestBody ${className} ${modelName})
        map.put("modelName", StringUtils.uncapitalize(className)); //模型名字
        // @RequestMapping("/${moduleName}/${pathName}")
        String moduleName = packageName.substring(packageName.lastIndexOf(".") + 1, packageName.length());
        map.put("moduleName", moduleName); //模块名字  包名(相对路径)
 
        String pathName = StrUtil.toSymbolCase(className, '/');// 驼峰转下划线
        if (pathName.indexOf(moduleName) == 0) {
            pathName = pathName.substring(moduleName.length());
            if (pathName.length() > 0 && pathName.startsWith("/")) {
                pathName = pathName.substring(1);
            }
        }
 
        map.put("importPath", tableName.replaceAll("_", "-"));// url请求的
        map.put("pathName", pathName);// url请求的
        map.put("permName", pathName.replace("/", ":"));// 权限的
        map.put("columns", columsList);
        map.put("selectColumns", columsList.stream().filter(column -> "true".equals(column.getIsSelectColumn()))
                .collect(Collectors.toList()));
 
        map.put("version", "1.0.0");
        map.put("author", "zt generator");
        map.put("email", "");
        map.put("isExport", isExport);
        map.put("hasBigDecimal", hasBigDecimal);
        map.put("hasDate", hasDate);
        map.put("datetime", DateUtil.now());
        map.put("date", DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMAT));
 
        for (int i = 0; i <= 10; i++) {
            map.put("id" + i, IdWorker.getId());
        }
 
        VelocityContext context = new VelocityContext(map);
 
        // 获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
 
            if (!"true".equals(isGenService) && (template.contains("Service") || template.contains("Controller"))) {
                continue;
            }
 
            if (!"true".equals(isPageFlag)
                    && (template.contains("index.vue") || template.contains("add-or-update.vue"))) {
                continue;
            }
 
            if (!"true".equals(isExport) && template.contains("Excel")) {
                continue;
            }
 
            // 渲染模板
            String fileName = "";
            String filePath = "";
            if (template.contains("index.vue")) {
                fileName = className + ".vue";
                filePath = getFilePath(template, vueFilePath, packageName, moduleName);
            } else if (template.contains("add-or-update.vue")) {
                fileName = className + "-AddOrUpdate.vue";
                filePath = getFilePath(template, vueFilePath, packageName, moduleName);
            } else if (template.contains("Entity.java.vm")) {
                fileName = className + ".java";
                filePath = getFilePath(template, javaFilePath, packageName, moduleName);
            } else {
                fileName = className + template.split("/")[1].replaceAll(".vm", "");
                filePath = getFilePath(template, javaFilePath, packageName, moduleName);
            }
            FileUtil.mkdir(filePath);
            try {
                Writer writer = new OutputStreamWriter(new FileOutputStream(filePath + "/" + fileName), "UTF-8");
                Template tpl = Velocity.getTemplate(template, "UTF-8");
                tpl.merge(context, writer);
                writer.flush();
                writer.close();
                System.out.println("生成" + fileName + "成功,目录:" + filePath);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RenException(e.getMessage());
            }
        }
    }
 
    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[] { '_' }).replace("_", "");
    }
 
    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "");
        }
        return columnToJava(tableName);
    }
 
    /**
     * 获取文件名
     */
    public static String getFilePath(String template, String filePath, String packageName, String moduleName) {
 
        if (template.contains("Entity.java.vm")) {
            return filePath + "/src/main/java/" + packageName.replace(".", "/") + "/model";
        }
 
        if (template.contains("Excel.java.vm")) {
            return filePath + "/src/main/java/" + packageName.replace(".", "/") + "/excel";
        }
 
        if (template.contains("Dao.java.vm")) {
            return filePath + "/src/main/java/" + packageName.replace(".", "/") + "/dao";
        }
 
        if (template.contains("Service.java.vm")) {
            return filePath + "/src/main/java/" + packageName.replace(".", "/") + "/service";
        }
 
        if (template.contains("Controller.java.vm")) {
            return filePath + "/src/main/java/" + packageName.replace(".", "/") + "/controller";
        }
 
        if (template.contains("Dao.xml.vm")) {
            return filePath + "/src/main/resources/mapper/" + moduleName;
        }
 
        if (template.contains("index.vue.vm")) {
            return filePath + "/src/views/modules/"
                    + packageName.substring(packageName.lastIndexOf(".") + 1, packageName.length());
        }
 
        if (template.contains("add-or-update.vue.vm")) {
            return filePath + "/src/views/modules/"
                    + packageName.substring(packageName.lastIndexOf(".") + 1, packageName.length());
        }
 
        if (template.contains("mysql.vm")) {
            return filePath + "/src/main/java/" + packageName.replace(".", "/") + "/mysql";
        }
 
        return null;
    }
 
    private static Map<String, String> map = new HashMap() {
        {
            put("tinyint".toUpperCase(), "Integer");
            put("smallint".toUpperCase(), "Integer");
            put("mediumint".toUpperCase(), "Integer");
            put("int".toUpperCase(), "Integer");
            put("integer".toUpperCase(), "Integer");
            put("bigint".toUpperCase(), "Long");
            put("float".toUpperCase(), "Float");
            put("double".toUpperCase(), "Double");
            put("decimal".toUpperCase(), "BigDecimal");
            put("char".toUpperCase(), "String");
            put("varchar".toUpperCase(), "String");
            put("tinytext".toUpperCase(), "String");
            put("text".toUpperCase(), "String");
            put("mediumtext".toUpperCase(), "String");
            put("longtext".toUpperCase(), "String");
            put("date".toUpperCase(), "Date");
            put("datetime".toUpperCase(), "Date");
            put("timestamp".toUpperCase(), "Date");
            put("NUMBER", "Integer");
            put("INT".toLowerCase(), "Integer");
            put("INTEGER", "Integer");
            put("BINARY_INTEGER", "Integer");
            put("LONG", "String");
            put("FLOAT", "Float");
            put("BINARY_FLOAT", "Float");
            put("DOUBLE", "Double");
            put("BINARY_DOUBLE", "Double");
            put("DECIMAL", "BigDecimal");
            put("CHAR", "String");
            put("VARCHAR", "String");
            put("VARCHAR2", "String");
            put("NVARCHAR", "String");
            put("NVARCHAR2", "String");
            put("CLOB", "String");
            put("BLOB", "String");
            put("DATE", "Date");
            put("DATETIME", "Date");
            put("TIMESTAMP", "Date");
            put("TIMESTAMP(6);", "Date");
            put("int8", "Long");
            put("int4", "Integer");
            put("int2", "Integer");
            put("numeric", "BigDecimal");
            put("INT16", "Short");
            put("INT32", "Integer");
            put("INT64", "Long");
            put("BIGINT", "Long");
            put("TINYINT UNSIGNED", "Integer");
            put("TINYINT", "Integer");
            put("BIT", "Boolean");
        }
    };
}