mybatis-plus代码生成
jerry2 Architect

添加依赖

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<!-- freemarker模板引擎依赖-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>

核心代码

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
package top.diruipu.demo.server.generator;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
* @author diruipu
* @create 2022-04-07 2:00 PM
* @ClassName Generator
*/
public class Generator {

//表名,多个英文逗号分割
private static String tableNames="t_log_copy";
//数据库链接
private static String dataSourceUrl="jdbc:mysql://192.168.0.108:3306/demo?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai";
//数据库驱动
private static String dataSourceDriver="com.mysql.cj.jdbc.Driver";
//账号
private static String dataSourceUser="root";
//密码
private static String dataSourcePwd="root";

public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
String projectPath = System.getProperty("user.dir");
// 全局配置
setGlobalConfig(mpg,projectPath);
// 数据源配置
setDataSourceConfig(mpg);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("cc.mrbird. .server.system");
mpg.setPackageInfo(pc);
// 自定义配置
setCfg(mpg,projectPath,pc);
// 配置模板
setTemplate(mpg);
// 策略配置
// true 通过上方配置tableNames来读取表名
// false 通过控制台扫描输入来获取表名
setStrategy(mpg,false);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}



public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}

/**
* 全局配置
* */
private static void setGlobalConfig(AutoGenerator mpg,String projectPath){
GlobalConfig gc = new GlobalConfig();
//生成system目录下
gc.setOutputDir(projectPath + "/ -server/ -server-system/src/main/java")
.setActiveRecord(false) // 是否支持AR模式
.setAuthor("zrp") //生成作者注释
.setOpen(false) //生成后是否打开资源管理器
.setBaseColumnList(true) //生成基本的SQL片段
.setBaseResultMap(true) //生成基本的resultMap
.setEnableCache(false) // XML 二级缓存
.setIdType(IdType.UUID) // 主键策略
.setDateType(DateType.ONLY_DATE)//定义生成的实体类中日期类型
.setSwagger2(true);//实体属性 Swagger2 注解

mpg.setGlobalConfig(gc);
}

private static void setDataSourceConfig(AutoGenerator mpg){
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dataSourceUrl);
// dsc.setSchemaName("public");
dsc.setDriverName(dataSourceDriver);
dsc.setUsername(dataSourceUser);
dsc.setPassword(dataSourcePwd);
mpg.setDataSource(dsc);
}

private static void setCfg(AutoGenerator mpg,String projectPath,PackageConfig pc){
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};

// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + (pc.getModuleName()==null?"":pc.getModuleName()+"/")
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});

cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);

}
private static void setTemplate(AutoGenerator mpg){
TemplateConfig templateConfig = new TemplateConfig();

// 配置自定义输出模板
templateConfig.setService("/generator/templates/service.java");
templateConfig.setServiceImpl("/generator/templates/serviceImpl.java");
templateConfig.setController("/generator/templates/controller.java");
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
}
private static void setStrategy(AutoGenerator mpg,Boolean isScannerTableName){
StrategyConfig strategy = new StrategyConfig();

strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);

if (Boolean.TRUE.equals(isScannerTableName)){
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
}else{
strategy.setInclude(tableNames.split(","));
}

strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("t_");
mpg.setStrategy(strategy);
}

}

模版配置

service模版

文件名:service.java.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
package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};

import top.diruipu.demo.common.core.entity.QueryRequest;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
* <p>
* ${table.comment!} 服务类
* </p>
*
* @author ${author}
* @since ${date}
*/
public interface I${entity}Service extends IService<${entity}> {
/**
* 查询(分页)
*
* @param request QueryRequest
* @param ${entity?uncap_first} ${entity?uncap_first}
* @return IPage<${entity}>
*/
IPage<${entity}> find${entity}s(QueryRequest request, ${entity} ${entity?uncap_first});

/**
* 查询(所有)
*
* @param ${entity?uncap_first} ${entity?uncap_first}
* @return List<${entity}>
*/
List<${entity}> find${entity}s(${entity} ${entity?uncap_first});

/**
* 新增
*
* @param ${entity?uncap_first} ${entity?uncap_first}
*/
void create${entity}(${entity} ${entity?uncap_first});

/**
* 修改
*
* @param ${entity?uncap_first} ${entity?uncap_first}
*/
void update${entity}(${entity} ${entity?uncap_first});

/**
* 删除
*
* @param ${entity?uncap_first} ${entity?uncap_first}
*/
void delete${entity}(${entity} ${entity?uncap_first});
}

serviceImpl模版

文件名:serviceImpl.java.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
69
package ${package.ServiceImpl};

import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import top.diruipu.demo.common.core.entity.QueryRequest;

import java.util.List;

/**
* <p>
* ${table.comment!} 服务实现类
* </p>
*
* @author ${author}
* @since ${date}
*/

@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

private final ${table.mapperName} ${table.mapperName?uncap_first};

@Override
public IPage<${entity}> find${entity}s(QueryRequest request, ${entity} ${entity?uncap_first}) {
LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>();
// TODO 设置查询条件
Page<${entity}> page = new Page<>(request.getPageNum(), request.getPageSize());
return this.page(page, queryWrapper);
}

@Override
public List<${entity}> find${entity}s(${entity} ${entity?uncap_first}) {
LambdaQueryWrapper<${entity}> queryWrapper = new LambdaQueryWrapper<>();
// TODO 设置查询条件
return this.baseMapper.selectList(queryWrapper);
}

@Override
@Transactional(rollbackFor = Exception.class)
public void create${entity}(${entity} ${entity?uncap_first}) {
this.save(${entity?uncap_first});
}

@Override
@Transactional(rollbackFor = Exception.class)
public void update${entity}(${entity} ${entity?uncap_first}) {
this.saveOrUpdate(${entity?uncap_first});
}

@Override
@Transactional(rollbackFor = Exception.class)
public void delete${entity}(${entity} ${entity?uncap_first}) {
LambdaQueryWrapper<${entity}> wapper = new LambdaQueryWrapper<>();
// TODO 设置删除条件
this.remove(wapper);
}

}

Controller模版

文件名:controller.java.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
69
70
71
72
73
74
75
76
77
78
79
package ${package.Controller};

import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import top.diruipu.demo.common.core.entity.Response;
import top.diruipu.demo.common.core.entity.QueryRequest;
import top.diruipu.demo.common.core.exception.SysException;
import top.diruipu.demo.common.core.utils.SysUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
* <p>
* ${table.comment!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
@Slf4j
@Validated
@RestController
@RequestMapping("${entity?uncap_first}")
@RequiredArgsConstructor
public class ${entity}Controller {

private final I${entity}Service ${entity?uncap_first}Service;

@GetMapping
public Response getAll${entity}s(${entity} ${entity?uncap_first}) {
return new Response().data(${entity?uncap_first}Service.find${entity}s(${entity?uncap_first}));
}

@GetMapping("list")
public Response ${entity?uncap_first}List(QueryRequest request, ${entity} ${entity?uncap_first}) {
Map<String, Object> dataTable = SysUtil.getDataTable(this.${entity?uncap_first}Service.find${entity}s(request, ${entity?uncap_first}));
return new Response().data(dataTable);
}

@PostMapping
public void add${entity}(@Valid ${entity} ${entity?uncap_first}) throws Exception {
try {
this.${entity?uncap_first}Service.create${entity}(${entity?uncap_first});
} catch (Exception e) {
String message = "新增${entity}失败";
log.error(message, e);
throw new SysException(message);
}
}

@DeleteMapping
public void delete${entity}(${entity} ${entity?uncap_first}) throws Exception {
try {
this.${entity?uncap_first}Service.delete${entity}(${entity?uncap_first});
} catch (Exception e) {
String message = "删除${entity}失败";
log.error(message, e);
throw new SysException(message);
}
}

@PutMapping
public void update${entity}(${entity} ${entity?uncap_first}) throws Exception {
try {
this.${entity?uncap_first}Service.update${entity}(${entity?uncap_first});
} catch (Exception e) {
String message = "修改${entity}失败";
log.error(message, e);
throw new SysException(message);
}
}
}

相关代码参考

Response
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

import java.util.HashMap;


public class Response extends HashMap<String, Object> {


public Response message(String message) {
this.put("message", message);
return this;
}

public Response data(Object data) {
this.put("data", data);
return this;
}

@Override
public Response put(String key, Object value) {
super.put(key, value);
return this;
}

public String getMessage() {
return String.valueOf(get("message"));
}

public Object getData() {
return get("data");
}
}

QueryRequest
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

import lombok.Data;
import lombok.ToString;

import java.io.Serializable;

@Data
@ToString
public class QueryRequest implements Serializable {

/**
* 当前页面数据量
*/
private int pageSize = 10;
/**
* 当前页码
*/
private int pageNum = 1;
/**
* 排序字段
*/
private String field;
/**
* 排序规则,asc升序,desc降序
*/
private String order;
}

SysException
1
2
3
4
5
6
7

public class SysException extends RuntimeException {

public SysException(String message) {
super(message);
}
}
SysUtil
1
2
3
4
5
6
7
8
public abstract class SysUtil {
public static Map<String, Object> getDataTable(IPage<?> pageInfo) {
Map<String, Object> data = new HashMap<>(4);
data.put("rows", pageInfo.getRecords());
data.put("total", pageInfo.getTotal());
return data;
}
}
 评论