GenUtil.java 12.6 KB
Newer Older
1
package me.zhengjie.utils;
2

3
import cn.hutool.core.util.StrUtil;
4 5
import cn.hutool.extra.template.*;
import lombok.extern.slf4j.Slf4j;
6
import me.zhengjie.domain.GenConfig;
D
dqjdda 已提交
7
import me.zhengjie.domain.ColumnInfo;
8 9 10 11 12 13 14 15 16 17 18 19 20
import org.springframework.util.ObjectUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成
21
 * @author Zheng Jie
22 23 24 25 26 27 28 29 30
 * @date 2019-01-02
 */
@Slf4j
public class GenUtil {

    private static final String TIMESTAMP = "Timestamp";

    private static final String BIGDECIMAL = "BigDecimal";

31
    public static final String PK = "PRI";
32

33
    public static final String EXTRA = "auto_increment";
34

35 36
    /**
     * 获取后端代码模板名称
37
     * @return List
38
     */
39
    private static List<String> getAdminTemplateNames() {
40 41 42 43 44 45 46
        List<String> templateNames = new ArrayList<>();
        templateNames.add("Entity");
        templateNames.add("Dto");
        templateNames.add("Mapper");
        templateNames.add("Repository");
        templateNames.add("Service");
        templateNames.add("ServiceImpl");
47
        templateNames.add("QueryCriteria");
48 49 50 51 52 53
        templateNames.add("Controller");
        return templateNames;
    }

    /**
     * 获取前端代码模板名称
54
     * @return List
55
     */
56
    private static List<String> getFrontTemplateNames() {
57 58 59 60 61 62 63
        List<String> templateNames = new ArrayList<>();
        templateNames.add("api");
        templateNames.add("index");
        templateNames.add("eForm");
        return templateNames;
    }

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
    public static void generatorCode(List<ColumnInfo> columnInfos, GenConfig genConfig) throws IOException {
        // 存储模版字段数据
        Map<String,Object> genMap = new HashMap<>();
        // 包名称
        genMap.put("package",genConfig.getPack());
        // 模块名称
        genMap.put("moduleName",genConfig.getModuleName());
        // 作者
        genMap.put("author",genConfig.getAuthor());
        // 创建日期
        genMap.put("date", LocalDate.now().toString());
        // 表名
        genMap.put("tableName",genConfig.getTableName());
        // 大写开头的类名
        String className = StringUtils.toCapitalizeCamelCase(genConfig.getTableName());
        // 小写开头的类名
        String changeClassName = StringUtils.toCamelCase(genConfig.getTableName());
81 82
        // 判断是否去除表前缀
        if (StringUtils.isNotEmpty(genConfig.getPrefix())) {
83 84
            className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTableName(),genConfig.getPrefix()));
            changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTableName(),genConfig.getPrefix()));
85
        }
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        // 保存类名
        genMap.put("className", className);
        // 保存小写开头的类名
        genMap.put("changeClassName", changeClassName);
        // 存在 Timestamp 字段
        genMap.put("hasTimestamp",false);
        // 查询类中存在 Timestamp 字段
        genMap.put("queryHasTimestamp",false);
        // 存在 BigDecimal 字段
        genMap.put("hasBigDecimal",false);
        // 查询类中存在 BigDecimal 字段
        genMap.put("queryHasBigDecimal",false);
        // 是否需要创建查询
        genMap.put("hasQuery",false);
        // 自增主键
        genMap.put("auto",false);
        // 存在字典
        genMap.put("hasDict",false);
        // 存在日期注解
        genMap.put("hasDateAnnotation",false);
        // 保存字段信息
107
        List<Map<String,Object>> columns = new ArrayList<>();
108
        // 保存查询字段的信息
109
        List<Map<String,Object>> queryColumns = new ArrayList<>();
110 111 112 113 114 115 116
        // 存储字典信息
        List<String> dicts = new ArrayList<>();
        // 存储 DateRange 信息
        List<Map<String,Object>> dateRanges = new ArrayList<>();
        // 存储不为空的字段信息
        List<Map<String,Object>> isNotNullColumns = new ArrayList<>();

117
        for (ColumnInfo column : columnInfos) {
118
            Map<String,Object> listMap = new HashMap<>();
119 120 121
            // 字段描述
            listMap.put("remark",column.getRemark());
            // 字段类型
D
dqjdda 已提交
122
            listMap.put("columnKey",column.getKeyType());
123 124 125
            // 主键类型
            String colType = ColUtil.cloToJava(column.getColumnType());
            // 小写开头的字段名
126
            String changeColumnName = StringUtils.toCamelCase(column.getColumnName().toString());
127
            // 大写开头的字段名
128
            String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName().toString());
D
dqjdda 已提交
129
            if(PK.equals(column.getKeyType())){
130 131 132 133 134 135
                // 存储主键类型
                genMap.put("pkColumnType",colType);
                // 存储小写开头的字段名
                genMap.put("pkChangeColName",changeColumnName);
                // 存储大写开头的字段名
                genMap.put("pkCapitalColName",capitalColumnName);
136
            }
137
            // 是否存在 Timestamp 类型的字段
138
            if(TIMESTAMP.equals(colType)){
139
                genMap.put("hasTimestamp",true);
140
            }
141
            // 是否存在 BigDecimal 类型的字段
142
            if(BIGDECIMAL.equals(colType)){
143
                genMap.put("hasBigDecimal",true);
144
            }
145
            // 主键是否自增
146
            if(EXTRA.equals(column.getExtra())){
147 148 149 150 151 152
                genMap.put("auto",true);
            }
            // 主键存在字典
            if(StringUtils.isNotBlank(column.getDictName())){
                genMap.put("hasDict",true);
                dicts.add(column.getDictName());
153
            }
154 155

            // 存储字段类型
156
            listMap.put("columnType",colType);
157
            // 存储字原始段名称
158
            listMap.put("columnName",column.getColumnName());
159 160 161
            // 不为空
            listMap.put("istNotNull",column.getNotNull());
            // 字段列表显示
D
dqjdda 已提交
162
            listMap.put("columnShow",column.getListShow());
163 164 165 166 167
            // 表单显示
            listMap.put("formShow",column.getFormShow());
            // 表单组件类型
            listMap.put("formType",column.getFormType());
            // 小写开头的字段名称
168
            listMap.put("changeColumnName",changeColumnName);
169
            //大写开头的字段名称
170
            listMap.put("capitalColumnName",capitalColumnName);
171 172 173 174 175 176 177 178 179 180 181 182 183
            // 字典名称
            listMap.put("dictName",column.getDictName());
            // 关联字段
            listMap.put("joinName",column.getJoinName());
            // 日期注解
            listMap.put("dateAnnotation",column.getDateAnnotation());
            if(StringUtils.isNotBlank(column.getDateAnnotation())){
                genMap.put("hasDateAnnotation",true);
            }
            // 添加非空字段信息
            if(column.getNotNull()){
                isNotNullColumns.add(listMap);
            }
184
            // 判断是否有查询,如有则把查询的字段set进columnQuery
D
dqjdda 已提交
185
            if(!StringUtils.isBlank(column.getQueryType())){
186 187 188 189
                // 查询类型
                listMap.put("queryType",column.getQueryType());
                // 是否存在查询
                genMap.put("hasQuery",true);
190
                if(TIMESTAMP.equals(colType)){
191 192
                    // 查询中存储 Timestamp 类型
                    genMap.put("queryHasTimestamp",true);
193 194
                }
                if(BIGDECIMAL.equals(colType)){
195 196 197 198 199 200 201 202
                    // 查询中存储 BigDecimal 类型
                    genMap.put("queryHasBigDecimal",true);
                }
                if("DateRange".equalsIgnoreCase(column.getQueryType())){
                    dateRanges.add(listMap);
                } else {
                    // 添加到查询列表中
                    queryColumns.add(listMap);
203
                }
204
            }
205
            // 添加到字段列表中
206
            columns.add(listMap);
207
        }
208 209 210 211 212 213 214 215 216 217
        // 保存字段列表
        genMap.put("columns",columns);
        // 保存查询列表
        genMap.put("queryColumns",queryColumns);
        // 保存字段列表
        genMap.put("dicts",dicts);
        // 保存查询列表
        genMap.put("dateRanges",dateRanges);
        // 保存非空字段信息
        genMap.put("isNotNullColumns",isNotNullColumns);
218 219 220 221 222 223 224
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
        // 生成后端代码
        List<String> templates = getAdminTemplateNames();
        for (String templateName : templates) {
            Template template = engine.getTemplate("generator/admin/"+templateName+".ftl");
            String filePath = getAdminFilePath(templateName,genConfig,className);

225
            assert filePath != null;
226 227 228
            File file = new File(filePath);

            // 如果非覆盖生成
229 230
            if(!genConfig.getCover() && FileUtil.exist(file)){
                continue;
231 232
            }
            // 生成代码
233
            genFile(file, template, genMap);
234 235 236 237 238 239
        }

        // 生成前端代码
        templates = getFrontTemplateNames();
        for (String templateName : templates) {
            Template template = engine.getTemplate("generator/front/"+templateName+".ftl");
240
            String filePath = getFrontFilePath(templateName,genConfig,genMap.get("changeClassName").toString());
241

242
            assert filePath != null;
243 244 245
            File file = new File(filePath);

            // 如果非覆盖生成
246 247
            if(!genConfig.getCover() && FileUtil.exist(file)){
                continue;
248 249
            }
            // 生成代码
250
            genFile(file, template, genMap);
251 252 253 254 255 256
        }
    }

    /**
     * 定义后端文件路径以及名称
     */
257
    private static String getAdminFilePath(String templateName, GenConfig genConfig, String className) {
258 259
        String projectPath = System.getProperty("user.dir") + File.separator + genConfig.getModuleName();
        String packagePath = projectPath + File.separator + "src" +File.separator+ "main" + File.separator + "java" + File.separator;
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        if (!ObjectUtils.isEmpty(genConfig.getPack())) {
            packagePath += genConfig.getPack().replace(".", File.separator) + File.separator;
        }

        if ("Entity".equals(templateName)) {
            return packagePath + "domain" + File.separator + className + ".java";
        }

        if ("Controller".equals(templateName)) {
            return packagePath + "rest" + File.separator + className + "Controller.java";
        }

        if ("Service".equals(templateName)) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }

        if ("ServiceImpl".equals(templateName)) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if ("Dto".equals(templateName)) {
            return packagePath + "service" + File.separator + "dto" + File.separator + className + "DTO.java";
        }

284 285
        if ("QueryCriteria".equals(templateName)) {
            return packagePath + "service" + File.separator + "dto" + File.separator + className + "QueryCriteria.java";
286 287
        }

288 289
        if ("Mapper".equals(templateName)) {
            return packagePath + "service" + File.separator + "mapper" + File.separator + className + "Mapper.java";
290 291 292 293 294 295 296 297 298 299 300 301
        }

        if ("Repository".equals(templateName)) {
            return packagePath + "repository" + File.separator + className + "Repository.java";
        }

        return null;
    }

    /**
     * 定义前端文件路径以及名称
     */
302
    private static String getFrontFilePath(String templateName, GenConfig genConfig, String apiName) {
303 304 305 306 307 308 309 310 311 312 313
        String path = genConfig.getPath();

        if ("api".equals(templateName)) {
            return genConfig.getApiPath() + File.separator + apiName + ".js";
        }

        if ("index".equals(templateName)) {
            return path  + File.separator + "index.vue";
        }

        if ("eForm".equals(templateName)) {
314
            return path  + File.separator + File.separator + "form.vue";
315 316 317 318
        }
        return null;
    }

319
    private static void genFile(File file, Template template, Map<String, Object> map) throws IOException {
320 321 322 323 324 325
        // 生成目标文件
        Writer writer = null;
        try {
            FileUtil.touch(file);
            writer = new FileWriter(file);
            template.render(map, writer);
326
        } catch (TemplateException | IOException e) {
327 328
            throw new RuntimeException(e);
        } finally {
329
            assert writer != null;
330 331 332 333
            writer.close();
        }
    }
}