0
# Code Generation
1
2
MyBatis-Plus provides a powerful code generator that automatically creates entity classes, mapper interfaces, service classes, and controller classes from database schemas with extensive customization options and multiple template engine support.
3
4
## Capabilities
5
6
### AutoGenerator
7
8
Main code generator class that orchestrates the generation process.
9
10
```java { .api }
11
/**
12
* Automatic code generator
13
*/
14
public class AutoGenerator {
15
16
/**
17
* Execute code generation
18
*/
19
public void execute();
20
21
/**
22
* Set global configuration
23
* @param globalConfig Global configuration
24
* @return AutoGenerator instance
25
*/
26
public AutoGenerator setGlobalConfig(GlobalConfig globalConfig);
27
28
/**
29
* Set data source configuration
30
* @param dataSourceConfig Data source configuration
31
* @return AutoGenerator instance
32
*/
33
public AutoGenerator setDataSourceConfig(DataSourceConfig dataSourceConfig);
34
35
/**
36
* Set package configuration
37
* @param packageConfig Package configuration
38
* @return AutoGenerator instance
39
*/
40
public AutoGenerator setPackageConfig(PackageConfig packageConfig);
41
42
/**
43
* Set strategy configuration
44
* @param strategyConfig Strategy configuration
45
* @return AutoGenerator instance
46
*/
47
public AutoGenerator setStrategyConfig(StrategyConfig strategyConfig);
48
49
/**
50
* Set template configuration
51
* @param templateConfig Template configuration
52
* @return AutoGenerator instance
53
*/
54
public AutoGenerator setTemplateConfig(TemplateConfig templateConfig);
55
56
/**
57
* Set injection configuration
58
* @param injectionConfig Injection configuration
59
* @return AutoGenerator instance
60
*/
61
public AutoGenerator setInjectionConfig(InjectionConfig injectionConfig);
62
}
63
```
64
65
### Configuration Classes
66
67
#### GlobalConfig
68
69
Global configuration for output directory, author, and generation options.
70
71
```java { .api }
72
/**
73
* Global configuration
74
*/
75
public class GlobalConfig {
76
77
/**
78
* Set output directory
79
* @param outputDir Output directory path
80
* @return GlobalConfig instance
81
*/
82
public GlobalConfig setOutputDir(String outputDir);
83
84
/**
85
* Set whether to override existing files
86
* @param fileOverride Override flag
87
* @return GlobalConfig instance
88
*/
89
public GlobalConfig setFileOverride(boolean fileOverride);
90
91
/**
92
* Set whether to open output directory after generation
93
* @param open Open flag
94
* @return GlobalConfig instance
95
*/
96
public GlobalConfig setOpen(boolean open);
97
98
/**
99
* Set author name
100
* @param author Author name
101
* @return GlobalConfig instance
102
*/
103
public GlobalConfig setAuthor(String author);
104
105
/**
106
* Set whether to enable Kotlin code generation
107
* @param enableKotlin Kotlin flag
108
* @return GlobalConfig instance
109
*/
110
public GlobalConfig setEnableKotlin(boolean enableKotlin);
111
112
/**
113
* Set whether to enable Swagger annotations
114
* @param swagger Swagger flag
115
* @return GlobalConfig instance
116
*/
117
public GlobalConfig setSwagger(boolean swagger);
118
119
/**
120
* Set date type strategy
121
* @param dateType Date type
122
* @return GlobalConfig instance
123
*/
124
public GlobalConfig setDateType(DateType dateType);
125
126
/**
127
* Set comment date format
128
* @param commentDate Comment date format
129
* @return GlobalConfig instance
130
*/
131
public GlobalConfig setCommentDate(String commentDate);
132
}
133
```
134
135
#### DataSourceConfig
136
137
Database connection configuration.
138
139
```java { .api }
140
/**
141
* Data source configuration
142
*/
143
public class DataSourceConfig {
144
145
/**
146
* Set database URL
147
* @param url Database URL
148
* @return DataSourceConfig instance
149
*/
150
public DataSourceConfig setUrl(String url);
151
152
/**
153
* Set database driver class name
154
* @param driverName Driver class name
155
* @return DataSourceConfig instance
156
*/
157
public DataSourceConfig setDriverName(String driverName);
158
159
/**
160
* Set database username
161
* @param username Username
162
* @return DataSourceConfig instance
163
*/
164
public DataSourceConfig setUsername(String username);
165
166
/**
167
* Set database password
168
* @param password Password
169
* @return DataSourceConfig instance
170
*/
171
public DataSourceConfig setPassword(String password);
172
173
/**
174
* Set schema name
175
* @param schemaName Schema name
176
* @return DataSourceConfig instance
177
*/
178
public DataSourceConfig setSchemaName(String schemaName);
179
180
/**
181
* Set database type
182
* @param dbType Database type
183
* @return DataSourceConfig instance
184
*/
185
public DataSourceConfig setDbType(DbType dbType);
186
}
187
```
188
189
#### PackageConfig
190
191
Package structure configuration for generated classes.
192
193
```java { .api }
194
/**
195
* Package configuration
196
*/
197
public class PackageConfig {
198
199
/**
200
* Set parent package name
201
* @param parent Parent package
202
* @return PackageConfig instance
203
*/
204
public PackageConfig setParent(String parent);
205
206
/**
207
* Set module name
208
* @param moduleName Module name
209
* @return PackageConfig instance
210
*/
211
public PackageConfig setModuleName(String moduleName);
212
213
/**
214
* Set entity package name
215
* @param entity Entity package
216
* @return PackageConfig instance
217
*/
218
public PackageConfig setEntity(String entity);
219
220
/**
221
* Set service package name
222
* @param service Service package
223
* @return PackageConfig instance
224
*/
225
public PackageConfig setService(String service);
226
227
/**
228
* Set service implementation package name
229
* @param serviceImpl Service implementation package
230
* @return PackageConfig instance
231
*/
232
public PackageConfig setServiceImpl(String serviceImpl);
233
234
/**
235
* Set mapper package name
236
* @param mapper Mapper package
237
* @return PackageConfig instance
238
*/
239
public PackageConfig setMapper(String mapper);
240
241
/**
242
* Set XML package name
243
* @param xml XML package
244
* @return PackageConfig instance
245
*/
246
public PackageConfig setXml(String xml);
247
248
/**
249
* Set controller package name
250
* @param controller Controller package
251
* @return PackageConfig instance
252
*/
253
public PackageConfig setController(String controller);
254
255
/**
256
* Set path info for custom paths
257
* @param pathInfo Path information map
258
* @return PackageConfig instance
259
*/
260
public PackageConfig setPathInfo(Map<String, String> pathInfo);
261
}
262
```
263
264
## Usage Examples
265
266
**Basic Code Generation:**
267
268
```java
269
// Basic setup
270
AutoGenerator generator = new AutoGenerator();
271
272
// Global config
273
GlobalConfig globalConfig = new GlobalConfig();
274
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java")
275
.setAuthor("MyBatis-Plus Generator")
276
.setFileOverride(true)
277
.setOpen(false)
278
.setSwagger(true);
279
280
// Data source config
281
DataSourceConfig dataSourceConfig = new DataSourceConfig();
282
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8")
283
.setDriverName("com.mysql.cj.jdbc.Driver")
284
.setUsername("root")
285
.setPassword("password");
286
287
// Package config
288
PackageConfig packageConfig = new PackageConfig();
289
packageConfig.setParent("com.example")
290
.setModuleName("demo")
291
.setEntity("entity")
292
.setMapper("mapper")
293
.setService("service")
294
.setServiceImpl("service.impl")
295
.setController("controller");
296
297
// Strategy config
298
StrategyConfig strategyConfig = new StrategyConfig();
299
strategyConfig.setInclude("user", "department") // Tables to generate
300
.setNaming(NamingStrategy.underline_to_camel)
301
.setColumnNaming(NamingStrategy.underline_to_camel)
302
.setEntityLombokModel(true)
303
.setRestControllerStyle(true)
304
.setControllerMappingHyphenStyle(true);
305
306
// Execute generation
307
generator.setGlobalConfig(globalConfig)
308
.setDataSourceConfig(dataSourceConfig)
309
.setPackageConfig(packageConfig)
310
.setStrategyConfig(strategyConfig)
311
.execute();
312
```
313
314
**Advanced Configuration:**
315
316
```java
317
AutoGenerator generator = new AutoGenerator();
318
319
// Global config with advanced options
320
GlobalConfig globalConfig = new GlobalConfig();
321
globalConfig.setOutputDir("/path/to/output")
322
.setAuthor("Your Name")
323
.setFileOverride(true)
324
.setOpen(false)
325
.setEnableKotlin(false)
326
.setSwagger(true)
327
.setDateType(DateType.TIME_PACK)
328
.setCommentDate("yyyy-MM-dd HH:mm:ss");
329
330
// Strategy config with table and field settings
331
StrategyConfig strategyConfig = new StrategyConfig();
332
strategyConfig.setInclude("sys_user", "sys_role", "sys_permission")
333
.setExclude("temp_table")
334
.setNaming(NamingStrategy.underline_to_camel)
335
.setColumnNaming(NamingStrategy.underline_to_camel)
336
.setTablePrefix("sys_")
337
.setFieldPrefix("f_")
338
.setEntityLombokModel(true)
339
.setEntityTableFieldAnnotationEnable(true)
340
.setEntityBooleanColumnRemoveIsPrefix(true)
341
.setRestControllerStyle(true)
342
.setControllerMappingHyphenStyle(true)
343
.setEntitySerialVersionUID(true)
344
.setEntityColumnConstant(true)
345
.setChainModel(true);
346
347
// Template config to customize generated files
348
TemplateConfig templateConfig = new TemplateConfig();
349
templateConfig.setEntity("/templates/entity.java.vm")
350
.setMapper("/templates/mapper.java.vm")
351
.setService("/templates/service.java.vm")
352
.setServiceImpl("/templates/serviceImpl.java.vm")
353
.setController("/templates/controller.java.vm")
354
.setXml("/templates/mapper.xml.vm");
355
356
generator.setGlobalConfig(globalConfig)
357
.setDataSourceConfig(dataSourceConfig)
358
.setPackageConfig(packageConfig)
359
.setStrategyConfig(strategyConfig)
360
.setTemplateConfig(templateConfig)
361
.execute();
362
```
363
364
**Custom Templates with Injection:**
365
366
```java
367
// Custom injection config
368
InjectionConfig injectionConfig = new InjectionConfig() {
369
@Override
370
public void initMap() {
371
Map<String, Object> map = new HashMap<>();
372
map.put("projectName", "MyProject");
373
map.put("basePackage", "com.example.demo");
374
map.put("author", "Generator");
375
map.put("version", "1.0.0");
376
this.setMap(map);
377
}
378
};
379
380
// Custom file output configs
381
List<FileOutConfig> focList = new ArrayList<>();
382
383
// Generate DTO classes
384
focList.add(new FileOutConfig("/templates/dto.java.vm") {
385
@Override
386
public String outputFile(TableInfo tableInfo) {
387
return "/path/to/dto/" + tableInfo.getEntityName() + "DTO.java";
388
}
389
});
390
391
// Generate VO classes
392
focList.add(new FileOutConfig("/templates/vo.java.vm") {
393
@Override
394
public String outputFile(TableInfo tableInfo) {
395
return "/path/to/vo/" + tableInfo.getEntityName() + "VO.java";
396
}
397
});
398
399
injectionConfig.setFileOutConfigList(focList);
400
401
generator.setInjectionConfig(injectionConfig);
402
```
403
404
**Multiple Template Engines:**
405
406
```java
407
// Using Velocity (default)
408
generator.setTemplateEngine(new VelocityTemplateEngine());
409
410
// Using Freemarker
411
generator.setTemplateEngine(new FreemarkerTemplateEngine());
412
413
// Using Beetl
414
generator.setTemplateEngine(new BeetlTemplateEngine());
415
416
// Using Enjoy
417
generator.setTemplateEngine(new EnjoyTemplateEngine());
418
```
419
420
**Generated Code Examples:**
421
422
Entity class generated:
423
```java
424
@Data
425
@EqualsAndHashCode(callSuper = false)
426
@Accessors(chain = true)
427
@TableName("sys_user")
428
@ApiModel(value="User对象", description="用户表")
429
public class User implements Serializable {
430
431
private static final long serialVersionUID = 1L;
432
433
@ApiModelProperty(value = "主键ID")
434
@TableId(value = "id", type = IdType.AUTO)
435
private Long id;
436
437
@ApiModelProperty(value = "用户名")
438
@TableField("username")
439
private String username;
440
441
@ApiModelProperty(value = "密码")
442
@TableField("password")
443
private String password;
444
445
@ApiModelProperty(value = "邮箱")
446
@TableField("email")
447
private String email;
448
449
@ApiModelProperty(value = "创建时间")
450
@TableField(value = "create_time", fill = FieldFill.INSERT)
451
private LocalDateTime createTime;
452
453
@ApiModelProperty(value = "更新时间")
454
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
455
private LocalDateTime updateTime;
456
}
457
```
458
459
Service interface generated:
460
```java
461
public interface UserService extends IService<User> {
462
}
463
```
464
465
Service implementation generated:
466
```java
467
@Service
468
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
469
}
470
```
471
472
Mapper interface generated:
473
```java
474
public interface UserMapper extends BaseMapper<User> {
475
}
476
```
477
478
Controller generated:
479
```java
480
@RestController
481
@RequestMapping("/user")
482
@Api(tags = "用户管理")
483
public class UserController {
484
485
@Autowired
486
private UserService userService;
487
488
@GetMapping("/list")
489
@ApiOperation("获取用户列表")
490
public R<List<User>> list() {
491
return R.ok(userService.list());
492
}
493
494
@PostMapping("/save")
495
@ApiOperation("保存用户")
496
public R<Boolean> save(@RequestBody User user) {
497
return R.ok(userService.save(user));
498
}
499
500
// ... other CRUD methods
501
}
502
```
503
504
This code generation system dramatically accelerates development by automatically creating boilerplate code while maintaining customization flexibility through templates and configuration options.