从零搭建自己的SpringBoot后台框架(十)

释放双眼,带上耳机,听听看~!

一:添加freemarker依赖


1
2
3
4
5
6
1<dependency>
2   <groupId>org.freemarker</groupId>
3   <artifactId>freemarker</artifactId>
4   <version>2.3.28</version>
5</dependency>
6

二:创建service,serviceImpl,controller模板

在src\test\java\resources\template\generator下创建

service.ftl

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1package ${basePackageService};
2
3import ${basePackageModel}.${modelNameUpperCamel};
4import ${basePackage}.core.universal.Service;
5
6/**
7* @Description: ${modelNameUpperCamel}Service接口
8* @author ${author}
9* @date ${date}
10*/
11public interface ${modelNameUpperCamel}Service extends Service<${modelNameUpperCamel}> {
12
13}
14

service-impl.ftl

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1package ${basePackageServiceImpl};
2
3import ${basePackageDao}.${modelNameUpperCamel}Mapper;
4import ${basePackageModel}.${modelNameUpperCamel};
5import ${basePackageService}.${modelNameUpperCamel}Service;
6import ${basePackage}.core.universal.AbstractService;
7import org.springframework.stereotype.Service;
8import org.springframework.transaction.annotation.Transactional;
9
10import javax.annotation.Resource;
11
12/**
13* @Description: ${modelNameUpperCamel}Service接口实现类
14* @author ${author}
15* @date ${date}
16*/
17@Service
18public class ${modelNameUpperCamel}ServiceImpl extends AbstractService<${modelNameUpperCamel}> implements ${modelNameUpperCamel}Service {
19
20    @Resource
21    private ${modelNameUpperCamel}Mapper ${modelNameLowerCamel}Mapper;
22
23}
24

controller.ftl

 


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
1package ${basePackageController};
2
3import ${basePackage}.core.ret.RetResult;
4import ${basePackage}.core.ret.RetResponse;
5import ${basePackageModel}.${modelNameUpperCamel};
6import ${basePackageService}.${modelNameUpperCamel}Service;
7import com.github.pagehelper.PageHelper;
8import com.github.pagehelper.PageInfo;
9import org.springframework.web.bind.annotation.PostMapping;
10import org.springframework.web.bind.annotation.RequestMapping;
11import org.springframework.web.bind.annotation.RequestParam;
12import org.springframework.web.bind.annotation.RestController;
13
14import javax.annotation.Resource;
15import java.util.List;
16
17/**
18* @Description: ${modelNameUpperCamel}Controller类
19* @author ${author}
20* @date ${date}
21*/
22@RestController
23@RequestMapping("/${baseRequestMapping}")
24public class ${modelNameUpperCamel}Controller {
25
26    @Resource
27    private ${modelNameUpperCamel}Service ${modelNameLowerCamel}Service;
28
29    @PostMapping("/insert")
30    public RetResult<Integer> insert(${modelNameUpperCamel} ${modelNameLowerCamel}) throws Exception{
31       Integer state = ${modelNameLowerCamel}Service.insert(${modelNameLowerCamel});
32        return RetResponse.makeOKRsp(state);
33    }
34
35    @PostMapping("/deleteById")
36    public RetResult<Integer> deleteById(@RequestParam String id) throws Exception {
37        Integer state = ${modelNameLowerCamel}Service.deleteById(id);
38        return RetResponse.makeOKRsp(state);
39    }
40
41    @PostMapping("/update")
42    public RetResult<Integer> update(${modelNameUpperCamel} ${modelNameLowerCamel}) throws Exception {
43        Integer state = ${modelNameLowerCamel}Service.update(${modelNameLowerCamel});
44        return RetResponse.makeOKRsp(state);
45    }
46
47    @PostMapping("/selectById")
48    public RetResult<${modelNameUpperCamel}> selectById(@RequestParam String id) throws Exception {
49        ${modelNameUpperCamel} ${modelNameLowerCamel} = ${modelNameLowerCamel}Service.selectById(id);
50        return RetResponse.makeOKRsp(${modelNameLowerCamel});
51    }
52
53    /**
54     * @Description: 分页查询
55     * @param page 页码
56     * @param size 每页条数
57     * @Reutrn RetResult<PageInfo<${modelNameUpperCamel}>>
58     */
59    @PostMapping("/list")
60    public RetResult<PageInfo<${modelNameUpperCamel}>> list(@RequestParam(defaultValue = "0") Integer page,
61               @RequestParam(defaultValue = "0") Integer size) throws Exception {
62        PageHelper.startPage(page, size);
63        List<${modelNameUpperCamel}> list = ${modelNameLowerCamel}Service.selectAll();
64        PageInfo<${modelNameUpperCamel}> pageInfo = new PageInfo<${modelNameUpperCamel}>(list);
65        return RetResponse.makeOKRsp(pageInfo);
66    }
67}
68

三:修改上篇文章中提到的CodeGenerator为如下


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
1package com.example.demo;
2
3import com.example.demo.core.constant.ProjectConstant;
4import com.google.common.base.CaseFormat;
5import freemarker.template.TemplateExceptionHandler;
6import org.apache.commons.lang3.StringUtils;
7import org.mybatis.generator.api.MyBatisGenerator;
8import org.mybatis.generator.config.*;
9import org.mybatis.generator.internal.DefaultShellCallback;
10
11import java.io.File;
12import java.io.FileWriter;
13import java.io.IOException;
14import java.text.SimpleDateFormat;
15import java.util.*;
16
17/**
18 * @author phubing
19 * @Description: 代码生成器,根据数据表名称生成对应的Model、Mapper、Service、Controller简化开发。
20 * @date 2019/4/23 20:28
21 */
22public class CodeGenerator {
23
24    // JDBC配置,请修改为你项目的实际配置
25    private static final String JDBC_URL = "jdbc:mysql://localhost:3333/demo";
26    private static final String JDBC_USERNAME = "root";
27    private static final String JDBC_PASSWORD = "123456";
28    private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
29    // 模板位置
30    private static final String TEMPLATE_FILE_PATH = "src/test/java/resources/template/generator";
31    private static final String JAVA_PATH = "src/main/java"; // java文件路径
32    private static final String RESOURCES_PATH = "src/main/resources";// 资源文件路径
33    // 生成的Service存放路径
34    private static final String PACKAGE_PATH_SERVICE = packageConvertPath(ProjectConstant.SERVICE_PACKAGE);
35    // 生成的Service实现存放路径
36    private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(ProjectConstant.SERVICE_IMPL_PACKAGE);
37    // 生成的Controller存放路径
38    private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(ProjectConstant.CONTROLLER_PACKAGE);
39
40    // @author
41    private static final String AUTHOR = "张瑶";
42    // @date
43    private static final String DATE = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new Date());
44
45    /**
46     * genCode("输入表名");
47     * @param args
48     */
49    public static void main(String[] args) {
50        genCode("system_log");
51    }
52
53    /**
54     * 通过数据表名称生成代码,Model 名称通过解析数据表名称获得,下划线转大驼峰的形式。 如输入表名称 "t_user_detail" 将生成
55     * TUserDetail、TUserDetailMapper、TUserDetailService ...
56     *
57     * @param tableNames 数据表名称...
58     */
59    public static void genCode(String... tableNames) {
60        for (String tableName : tableNames) {
61            genCode(tableName);
62        }
63    }
64
65    /**
66     * 通过数据表名称生成代码 如输入表名称 "user_info"
67     * 将生成 UserInfo、UserInfoMapper、UserInfoService ...
68     *
69     * @param tableName 数据表名称
70     */
71    public static void genCode(String tableName) {
72        genModelAndMapper(tableName);
73        genService(tableName);
74        genController(tableName);
75    }
76
77    public static void genModelAndMapper(String tableName) {
78        Context context = getContext();
79
80        JDBCConnectionConfiguration jdbcConnectionConfiguration = getJDBCConnectionConfiguration();
81        context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);
82
83        PluginConfiguration pluginConfiguration = getPluginConfiguration();
84        context.addPluginConfiguration(pluginConfiguration);
85
86        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = getJavaModelGeneratorConfiguration();
87        context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);
88
89        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = getSqlMapGeneratorConfiguration();
90        context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);
91
92        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = getJavaClientGeneratorConfiguration();
93        context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);
94
95        TableConfiguration tableConfiguration = new TableConfiguration(context);
96        tableConfiguration.setTableName(tableName);
97        tableConfiguration.setDomainObjectName(null);
98        context.addTableConfiguration(tableConfiguration);
99
100        List<String> warnings;
101        MyBatisGenerator generator;
102        try {
103            Configuration config = new Configuration();
104            config.addContext(context);
105            config.validate();
106            boolean overwrite = true;
107            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
108            warnings = new ArrayList<>();
109            generator = new MyBatisGenerator(config, callback, warnings);
110            generator.generate(null);
111        } catch (Exception e) {
112            throw new RuntimeException("生成Model和Mapper失败", e);
113        }
114
115        if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
116            throw new RuntimeException("生成Model和Mapper失败:" + warnings);
117        }
118        String modelName = tableNameConvertUpperCamel(tableName);
119        System.out.println(modelName + ".java 生成成功");
120        System.out.println(modelName + "Mapper.java 生成成功");
121        System.out.println(modelName + "Mapper.xml 生成成功");
122    }
123
124    public static void genService(String tableName) {
125        try {
126            freemarker.template.Configuration cfg = getConfiguration();
127            //模板所需要的参数
128            Map<String, Object> data = new HashMap<>();
129            data.put("date", DATE);
130            data.put("author", AUTHOR);
131            String modelNameUpperCamel = tableNameConvertUpperCamel(tableName);
132            data.put("modelNameUpperCamel", modelNameUpperCamel);
133            data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
134            data.put("basePackage", ProjectConstant.BASE_PACKAGE);
135            data.put("basePackageService", ProjectConstant.SERVICE_PACKAGE);
136            data.put("basePackageServiceImpl", ProjectConstant.SERVICE_IMPL_PACKAGE);
137            data.put("basePackageModel", ProjectConstant.MODEL_PACKAGE);
138            data.put("basePackageDao", ProjectConstant.MAPPER_PACKAGE);
139
140            File file = new File(JAVA_PATH + PACKAGE_PATH_SERVICE + modelNameUpperCamel + "Service.java");
141            if (!file.getParentFile().exists()) {
142                file.getParentFile().mkdirs();
143            }
144            cfg.getTemplate("service.ftl").process(data, new FileWriter(file));
145            System.out.println(modelNameUpperCamel + "Service.java 生成成功");
146
147            File file1 = new File(JAVA_PATH + PACKAGE_PATH_SERVICE_IMPL + modelNameUpperCamel + "ServiceImpl.java");
148            if (!file1.getParentFile().exists()) {
149                file1.getParentFile().mkdirs();
150            }
151            cfg.getTemplate("service-impl.ftl").process(data, new FileWriter(file1));
152            System.out.println(modelNameUpperCamel + "ServiceImpl.java 生成成功");
153        } catch (Exception e) {
154            throw new RuntimeException("生成Service失败", e);
155        }
156    }
157
158    public static void genController(String tableName) {
159        try {
160            freemarker.template.Configuration cfg = getConfiguration();
161            Map<String, Object> data = new HashMap<>();
162            data.put("date", DATE);
163            data.put("author", AUTHOR);
164            String modelNameUpperCamel = tableNameConvertUpperCamel(tableName);
165            data.put("baseRequestMapping", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
166            data.put("modelNameUpperCamel", modelNameUpperCamel);
167            data.put("modelNameLowerCamel", CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, modelNameUpperCamel));
168            data.put("basePackage", ProjectConstant.BASE_PACKAGE);
169            data.put("basePackageController", ProjectConstant.CONTROLLER_PACKAGE);
170            data.put("basePackageService", ProjectConstant.SERVICE_PACKAGE);
171            data.put("basePackageModel", ProjectConstant.MODEL_PACKAGE);
172
173            File file = new File(JAVA_PATH + PACKAGE_PATH_CONTROLLER + modelNameUpperCamel + "Controller.java");
174            if (!file.getParentFile().exists()) {
175                file.getParentFile().mkdirs();
176            }
177            cfg.getTemplate("controller.ftl").process(data, new FileWriter(file));
178
179            System.out.println(modelNameUpperCamel + "Controller.java 生成成功");
180        } catch (Exception e) {
181            throw new RuntimeException("生成Controller失败", e);
182        }
183
184    }
185
186    private static Context getContext() {
187        Context context = new Context(ModelType.FLAT);
188        context.setId("Potato");
189        context.setTargetRuntime("MyBatis3Simple");
190        context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
191        context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`");
192        return context;
193    }
194
195    private static JDBCConnectionConfiguration getJDBCConnectionConfiguration() {
196        JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
197        jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
198        jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
199        jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
200        jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
201        return jdbcConnectionConfiguration;
202    }
203
204    private static PluginConfiguration getPluginConfiguration() {
205        PluginConfiguration pluginConfiguration = new PluginConfiguration();
206        pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
207        pluginConfiguration.addProperty("mappers", ProjectConstant.MAPPER_INTERFACE_REFERENCE);
208        return pluginConfiguration;
209    }
210
211    private static JavaModelGeneratorConfiguration getJavaModelGeneratorConfiguration() {
212        JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
213        javaModelGeneratorConfiguration.setTargetProject(JAVA_PATH);
214        javaModelGeneratorConfiguration.setTargetPackage(ProjectConstant.MODEL_PACKAGE);
215        javaModelGeneratorConfiguration.addProperty("enableSubPackages", "true");
216        javaModelGeneratorConfiguration.addProperty("trimStrings", "true");
217        return javaModelGeneratorConfiguration;
218    }
219
220    private static SqlMapGeneratorConfiguration getSqlMapGeneratorConfiguration() {
221        SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
222        sqlMapGeneratorConfiguration.setTargetProject(RESOURCES_PATH);
223        sqlMapGeneratorConfiguration.setTargetPackage("mapper");
224        return sqlMapGeneratorConfiguration;
225    }
226
227    private static JavaClientGeneratorConfiguration getJavaClientGeneratorConfiguration() {
228        JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
229        javaClientGeneratorConfiguration.setTargetProject(JAVA_PATH);
230        javaClientGeneratorConfiguration.setTargetPackage(ProjectConstant.MAPPER_PACKAGE);
231        javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
232        return javaClientGeneratorConfiguration;
233    }
234
235    private static freemarker.template.Configuration getConfiguration() throws IOException {
236        freemarker.template.Configuration cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_23);
237        cfg.setDirectoryForTemplateLoading(new File(TEMPLATE_FILE_PATH));
238        cfg.setDefaultEncoding("UTF-8");
239        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
240        return cfg;
241    }
242
243    private static String tableNameConvertUpperCamel(String tableName) {
244        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase());
245    }
246
247    private static String packageConvertPath(String packageName) {
248        return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
249    }
250}
251
252

四:功能测试

在CodeGenerator中右键run

 

ok,创建成功

给TA打赏
共{{data.count}}人
人已打赏
安全技术

c++ list, vector, map, set 区别与用法比较

2022-1-11 12:36:11

安全技术

Node.js 应用故障排查手册 —— 利用 CPU 分析调优吞吐量 ...

2021-12-21 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索