一、配置
1<!-- Mybatis plus -->
2 <dependency>
3 <groupId>com.baomidou</groupId>
4 <artifactId>mybatis-plus-boot-starter</artifactId>
5 <version>3.1.1</version>
6 </dependency>
7 <!-- 自动生成代码 -->
8 <dependency>
9 <groupId>com.baomidou</groupId>
10 <artifactId>mybatis-plus-generator</artifactId>
11 <version>3.1.1</version>
12 </dependency>
13 <!-- 模板引擎 -->
14 <dependency>
15 <groupId>org.apache.velocity</groupId>
16 <artifactId>velocity-engine-core</artifactId>
17 <version>2.1</version>
18 </dependency>
19 <!-- lombok -->
20 <dependency>
21 <groupId>org.projectlombok</groupId>
22 <artifactId>lombok</artifactId>
23 <version>1.16.10</version>
24 </dependency>
二、生成代码类
1package com.czhappy.wanmathapi.generate;
2
3import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
4import com.baomidou.mybatisplus.core.toolkit.StringPool;
5import com.baomidou.mybatisplus.generator.AutoGenerator;
6import com.baomidou.mybatisplus.generator.InjectionConfig;
7import com.baomidou.mybatisplus.generator.config.*;
8import com.baomidou.mybatisplus.generator.config.po.TableInfo;
9import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
10import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
11import org.springframework.boot.jdbc.DataSourceBuilder;
12import org.springframework.jdbc.core.JdbcOperations;
13import org.springframework.jdbc.core.JdbcTemplate;
14import org.springframework.jdbc.core.SingleColumnRowMapper;
15import org.springframework.jdbc.datasource.DriverManagerDataSource;
16
17import javax.sql.DataSource;
18import java.io.File;
19import java.util.ArrayList;
20import java.util.HashMap;
21import java.util.List;
22import java.util.Map;
23import java.util.regex.Matcher;
24import java.util.regex.Pattern;
25
26public class MysqlGenerator {
27
28 private static final String database = "wanmath";
29 private static final String url = "jdbc:mysql://localhost:3306/" + database
30 + "?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC";
31 private static final String driverName = "com.mysql.jdbc.Driver";
32 private static final String userName = "root";
33 private static final String password = "root";
34
35 private static String basePath = "";
36 private static String mapperPath = "";
37
38
39 public static void main(String[] args) {
40 //生成代码,多张表用逗号分隔
41 generate("chenzheng","com.czhappy.wanmathapi", "tb_web_user");
42 }
43
44
45 47484950
51 public static void generate(String author, String packageName, String... tableNames) {
52
53 // 全局配置
54 GlobalConfig gc = initGlobalConfig(author, packageName);
55 // 数据源配置
56 DataSourceConfig dsc = initDataSourceConfig();
57 // 包配置
58 PackageConfig pc = new PackageConfig().setParent(packageName);
59 // 模板引擎配置
60 VelocityTemplateEngine templateEngine = new VelocityTemplateEngine();
61
62
63 //每一个entity都需要单独设置InjectionConfig, StrategyConfig和TemplateConfig
64 Map<String, String> names = new JdbcRepository().getEntityNames(tableNames);
65 if (names == null || names.isEmpty()) {
66 return;
67 }
68 for (String tableName : names.keySet()) {
69 // 代码生成器
70 AutoGenerator mpg = new AutoGenerator();
71 mpg.setGlobalConfig(gc);
72 mpg.setDataSource(dsc);
73 mpg.setPackageInfo(pc);
74 mpg.setTemplateEngine(templateEngine);
75
76 // 自定义配置
77 InjectionConfig cfg = initInjectionConfig(packageName);
78 mpg.setCfg(cfg);
79
80 // 策略配置
81 StrategyConfig strategy = initStrategyConfig(tableName);
82 mpg.setStrategy(strategy);
83
84 // 模板配置
85 // mapper文件
86 String mapperFile = mapperPath
87 + "/" + names.get(tableName) + "Mapper" + StringPool.DOT_XML;
88 TemplateConfig tc = initTemplateConfig(mapperFile);
89 mpg.setTemplate(tc);
90
91 //开始执行
92 mpg.execute();
93 }
94 }
95
96
97 99100
101 private static DataSourceConfig initDataSourceConfig() {
102 return new DataSourceConfig()
103 .setUrl(url)
104 .setDriverName(driverName)
105 .setUsername(userName)
106 .setPassword(password);
107 }
108
109 111112
113 private static GlobalConfig initGlobalConfig(String author, String packageName) {
114 GlobalConfig gc = new GlobalConfig();
115 String tmp = MysqlGenerator.class.getResource("").getPath();
116 String codeDir = tmp.substring(0, tmp.indexOf("/target"));
117 basePath = codeDir + "/src/main/java";
118 mapperPath = codeDir + "/src/main/resources/mapper";
119 System.out.println("basePath = " + basePath + "\nmapperPath = " + mapperPath);
120 gc.setOutputDir(basePath);
121 gc.setAuthor(author);
122 gc.setOpen(false);
123 gc.setServiceName("%sService");
124 gc.setFileOverride(true);
125
126 return gc;
127 }
128
129 131132133
134 private static InjectionConfig initInjectionConfig(String packageName) {
135 InjectionConfig cfg = new InjectionConfig() {
136 @Override
137 public void initMap() {
138 // to do nothing
139 }
140 };
141 List<FileOutConfig> focList = new ArrayList<>();
142 focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
143 @Override
144 public String outputFile(TableInfo tableInfo) {
145 //自定义输入文件名称
146 return mapperPath
147 + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
148 }
149 });
150 cfg.setFileOutConfigList(focList);
151
152 return cfg;
153 }
154
155 157158159
160 private static StrategyConfig initStrategyConfig(String tableName) {
161 StrategyConfig strategy = new StrategyConfig();
162 strategy.setNaming(NamingStrategy.underline_to_camel);
163 strategy.setColumnNaming(NamingStrategy.underline_to_camel);
164 strategy.setEntityLombokModel(true);
165 //strategy.setTablePrefix("tb");
166 strategy.setInclude(tableName);
167 strategy.setRestControllerStyle(true);
168
169 return strategy;
170 }
171
172 174175176
177 private static TemplateConfig initTemplateConfig(String mapperFile) {
178 TemplateConfig tc = new TemplateConfig();
179 tc.setXml(null);
180 //如果当前Entity已经存在,那么仅仅覆盖Entity
181 File file = new File(mapperFile);
182 System.out.println("file.exists()="+file.exists());
183 if (file.exists()) {
184 tc.setController(null);
185 tc.setMapper(null);
186 tc.setService(null);
187 tc.setServiceImpl(null);
188 tc.setEntityKt(null);
189 }
190
191 return tc;
192 }
193
194
195
196 public static class JdbcRepository {
197 private static Pattern linePattern = Pattern.compile("_(\\w)");
198 private JdbcOperations jdbcOperations;
199 public JdbcRepository() {
200 DataSource dataSource = DataSourceBuilder.create()
201 //如果不指定类型,那么默认使用连接池,会存在连接不能回收而最终被耗尽的问题
202 .type(DriverManagerDataSource.class)
203 .driverClassName(driverName)
204 .url(url)
205 .username(userName)
206 .password(password)
207 .build();
208 this.jdbcOperations = new JdbcTemplate(dataSource);
209 }
210
211 214215216
217 public Map<String, String> getEntityNames(String... tableNameArray) {
218 //该sql语句目前支持mysql
219 String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '" + database + "'";
220 if (tableNameArray != null && tableNameArray.length != 0) {
221 sql += " and (";
222 for (String name : tableNameArray) {
223 sql += " or table_name = '" + name + "'";
224 }
225 sql += ")";
226 }
227 sql = sql.replaceFirst("or", "");
228 List<String> tableNames = jdbcOperations.query(sql, SingleColumnRowMapper.newInstance(String.class));
229 if (CollectionUtils.isEmpty(tableNames)) {
230 return new HashMap<>();
231 }
232
233
234 Map<String, String> result = new HashMap<>();
235 tableNames.forEach(
236 tableName -> {
237 String entityName = underlineToCamel(tableName);
238// String prefix = "tb";
239// //如果有前缀,需要去掉前缀
240// if (tableName.startsWith(prefix)) {
241// String tableNameRemovePrefix = tableName.substring((prefix + "_").length());
242// entityName = underlineToCamel(tableNameRemovePrefix);
243// System.out.println("******"+entityName+"******");
244// }
245
246 result.put(tableName, entityName);
247 }
248 );
249
250
251 return result;
252 }
253
254
255 258259260
261 private static String underlineToCamel(String str) {
262 if (null == str || "".equals(str)) {
263 return str;
264 }
265 str = str.toLowerCase();
266 Matcher matcher = linePattern.matcher(str);
267 StringBuffer sb = new StringBuffer();
268 while (matcher.find()) {
269 matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
270 }
271 matcher.appendTail(sb);
272
273 str = sb.toString();
274 str = str.substring(0, 1).toUpperCase() + str.substring(1);
275
276 return str;
277 }
278
279 }
280}