xiangpei
2025-04-18 0aa739db8268b442ab74634289ffed00124a976a
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
package com.monkeylessey.gen.utils;
 
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.monkeylessey.sys.domain.base.AbsEntity;
import com.monkeylessey.gen.domain.GenerateData;
import com.monkeylessey.gen.enums.GenFileTypeEnum;
import com.monkeylessey.gen.engine.MyVelocityTemplateEngine;
import com.monkeylessey.sys.domain.vo.TableColumnVO;
import com.monkeylessey.sys.mapper.SysMenuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import javax.sql.DataSource;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
 
/**
 * 该类用于前端传递参数进行代码生成
 *
 * @author 29443
 * @date 2022/4/7
 */
@Service
public class GenerateCodeUtil {
 
    @Autowired
    private DataSource dataSource;
    @Autowired
    private SysMenuMapper sysMenuMapper;
 
    /**
     * 代码生成方法
     *
     * @param data 所需数据对象
     */
    public void generateCode(GenerateData data) {
        String outDir = "";
        String mapperDir = "";
        if (StringUtils.isNotBlank(data.getWhichModule())) {
            // 多模块应用
            outDir = System.getProperty("user.dir") + "\\" + data.getWhichModule() + "\\src\\main\\java";
            mapperDir = System.getProperty("user.dir") + "\\" + data.getWhichModule() + "\\src\\main\\resources\\mapper";
        } else {
            // 单模块应用
            outDir = System.getProperty("user.dir") + "\\src\\main\\java";
            mapperDir = System.getProperty("user.dir") + "\\src\\main\\resources\\mapper";
        }
 
        File outDirFile = new File(outDir);
        if (!outDirFile.exists()) {
            outDirFile.mkdirs();
        }
        File mapperDirFile = new File(mapperDir);
        if (!mapperDirFile.exists()) {
            mapperDirFile.mkdirs();
        }
 
        System.out.println(System.getProperty("user.dir"));
        String finalOutDir = outDir;
        String finalMapperDir = mapperDir;
 
        // 自定义vo、form、vue文件的的模板路径
        Map<String, String> customFileMap = new HashMap();
        customFileMap.put(GenFileTypeEnum.FORM.getValue(), "/templates/form.java.vm");
        customFileMap.put(GenFileTypeEnum.VO.getValue(), "/templates/vo.java.vm");
        customFileMap.put(GenFileTypeEnum.QUERY.getValue(), "/templates/query.java.vm");
        customFileMap.put(GenFileTypeEnum.VIEW.getValue(), "/templates/vueView.vue.vm");
        customFileMap.put(GenFileTypeEnum.DIALOG.getValue(), "/templates/vueDialog.vue.vm");
        customFileMap.put(GenFileTypeEnum.TABLE.getValue(), "/templates/vueTable.vue.vm");
        customFileMap.put(GenFileTypeEnum.STORE.getValue(), "/templates/vueStore.js.vm");
        customFileMap.put(GenFileTypeEnum.API.getValue(), "/templates/vueApi.js.vm");
 
        // 自定义数据
        Map<String, Object> customDataMap = new HashMap();
        // 数据校验分组
        customDataMap.put("addGroup", data.getAddGroupPath());
        customDataMap.put("updateGroup", data.getUpdateGroupPath());
        // 统一响应类
        customDataMap.put("responseDataName", data.getResponseClassName());
        customDataMap.put("responseDataPath", data.getResponseClassPath());
        // 分页类名
        customDataMap.put("pageClassName", data.getPageClassName());
        // 分页类所在路径
        customDataMap.put("pagePath", data.getPagePath());
 
        List<TableColumnVO> refColumnList = data.getColumns()
                .stream()
                .filter(item -> org.springframework.util.StringUtils.hasText(item.getRefColumn()))
                .collect(Collectors.toList());
        customDataMap.put("refColumnList", refColumnList);
        if (CollectionUtils.isEmpty(refColumnList)) {
            customDataMap.put("hasRef", Boolean.FALSE);
        } else {
            customDataMap.put("hasRef", Boolean.TRUE);
        }
        FastAutoGenerator.create(new DataSourceConfig.Builder(dataSource))
                .globalConfig(builder -> {
                    builder.author("向培")               //作者
                            .outputDir(finalOutDir)    //输出路径(写到java目录)
                            .enableSwagger()           //开启swagger
                            .commentDate("yyyy-MM-dd");
                    //.fileOverride();            //开启覆盖之前生成的文件
 
                })
                .packageConfig(builder -> {
                    builder.parent("com.monkeylessey")
                            //.moduleName("onceCode")
                            .entity("domain.entity")
                            .service("service")
                            .serviceImpl("service.impl")
                            .controller("controller")
                            .mapper("mapper")
                            .other("domain")
                            .xml("mapper")
                            .pathInfo(Collections.singletonMap(OutputFile.other, finalOutDir + "\\domain"))
                            .pathInfo(Collections.singletonMap(OutputFile.xml, finalMapperDir));
                })
                .strategyConfig(builder -> {
                    builder.addInclude(data.getTableName())
                            .addTablePrefix(data.getTablePrefix())
                            .serviceBuilder()
                            .formatServiceFileName("%sService")
                            .formatServiceImplFileName("%sServiceImpl")
                            .entityBuilder()
                            // 需要说明的是,父类是需要自己创建的,下面的父类字段也是你自己创建才行。plus不会说发现父类并没有id而创建id字段
                            .superClass(AbsEntity.class)
                            // 指定哪些字段在父表中,实体类将不会生成这些字段了
                            .addSuperEntityColumns("id", "gmt_create", "gmt_update", "deleted")
                            .enableLombok()
                            // 开启序列化
                            //.disableSerialVersionUID()
                            //.logicDeleteColumnName("deleted")
                            .enableTableFieldAnnotation()
                            .controllerBuilder()
                            // 映射路径使用连字符格式,而不是驼峰
                            .enableHyphenStyle()
                            .formatFileName("%sController")
                            .enableRestStyle()
                            .mapperBuilder()
                            //生成通用的resultMap
                            .enableBaseResultMap()
                            .superClass(BaseMapper.class)
                            .formatMapperFileName("%sMapper")
                            .enableMapperAnnotation()
                            .formatXmlFileName("%sMapper");
                })
                .injectionConfig(builder -> {
                    builder.customMap(customDataMap)
                            .customFile(customFileMap);
                })
                .templateConfig(new Consumer<TemplateConfig.Builder>() {
                    // 使用自定义entity模板
                    @Override
                    public void accept(TemplateConfig.Builder builder) {
                        builder.entity("templates/entity.java");
                    }
                })
                // 默认的是Velocity引擎模板
                .templateEngine(new MyVelocityTemplateEngine(data, sysMenuMapper))
                .execute();
    }
}