<properties>
<java.version>1.8</java.version>
<mybatis-plus-boot-starter.version>3.2.0</mybatis-plus-boot-starter.version>
<mybatis-plus-generator.version>3.2.0</mybatis-plus-generator.version>
<mybatis-plus-core.version>3.2.0</mybatis-plus-core.version>
<mybatis-plus-extension.version>3.2.0</mybatis-plus-extension.version>
</properties>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus-boot-starter.version}</version>
</dependency>
<!-- mybatis-plus -->
<!-- mybatis-plus自動生成代碼 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus-generator.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>${mybatis-plus-core.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${mybatis-plus-extension.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- mybatis-plus自動生成代碼 -->
package com.gyxmb.qywx;
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.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.util.CollectionUtils;
import javax.sql.DataSource;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyBatisPlusGenerator {
private static final String database = "數據庫名稱";
private static final String url = "jdbc:mysql://IP:3306/" + database + "?useUnicode=true&useSSL=false&characterEncoding=utf8";
private static final String driverName = "com.mysql.jdbc.Driver";
private static final String userName = "賬號";
private static final String password = "密碼";
private static String basePath = "";
private static String mapperPath = "";
public static void main(String[] args) {
generate("DuXueBo", "com.gyxmb.qywx", Arrays.asList(""), "t_");
}
/**
* 自動生成代碼
*
* @param author 作者
* @param packageName 包名
* @param tableList 具體表名稱集合
* @param tablePrefix 表前綴
*/
public static void generate(String author, String packageName, List<String> tableList, String... tablePrefix) {
// 全局配置
GlobalConfig gc = initGlobalConfig(author, packageName);
// 數據源配置
DataSourceConfig dsc = initDataSourceConfig();
// 包配置
PackageConfig pc = new PackageConfig().setParent(packageName);
// 模板引擎配置
FreemarkerTemplateEngine templateEngine = new FreemarkerTemplateEngine();
//每一個entity都需要單獨設置InjectionConfig, StrategyConfig和TemplateConfig
Map<String, String> names = new JdbcRepository().getEntityNames(tableList, tablePrefix);
if (names == null || names.isEmpty()) {
return;
}
for (String tableName : names.keySet()) {
// 代碼生成器
AutoGenerator mpg = new AutoGenerator();
mpg.setGlobalConfig(gc);
mpg.setDataSource(dsc);
mpg.setPackageInfo(pc);
mpg.setTemplateEngine(templateEngine);
// 自定義配置
InjectionConfig cfg = initInjectionConfig(packageName);
mpg.setCfg(cfg);
// 策略配置
StrategyConfig strategy = initStrategyConfig(tableName, tablePrefix);
mpg.setStrategy(strategy);
// 模板配置
// mapper文件
String mapperFile = mapperPath
+ "/" + names.get(tableName) + "Mapper" + StringPool.DOT_JAVA;
TemplateConfig tc = initTemplateConfig(mapperFile);
mpg.setTemplate(tc);
//開始執行
mpg.execute();
}
}
/**
* 配置數據源
*
* @return
*/
private static DataSourceConfig initDataSourceConfig() {
return new DataSourceConfig()
.setUrl(url)
.setDriverName(driverName)
.setUsername(userName)
.setPassword(password);
}
/**
* 全局配置
*
* @return
*/
private static GlobalConfig initGlobalConfig(String author, String packageName) {
GlobalConfig gc = new GlobalConfig();
String tmp = MyBatisPlusGenerator.class.getResource("").getPath();
String codeDir = tmp.substring(0, tmp.indexOf("/target"));
basePath = codeDir + "/src/main/java/temp";
mapperPath = basePath + "/" + packageName.replace(".", "/") + "/mapper";
System.out.println("basePath = " + basePath + "\nmapperPath = " + mapperPath);
gc.setOutputDir(basePath);
gc.setAuthor(author);
gc.setOpen(false);
gc.setSwagger2(true);
gc.setServiceName("%sService");
gc.setFileOverride(true);
return gc;
}
/**
* 自定義配置
*
* @param packageName
* @return
*/
private static InjectionConfig initInjectionConfig(String packageName) {
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
//自定義輸入文件名稱
return mapperPath
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
return cfg;
}
/**
* 策略配置
*
* @param tableName 數據庫表名
* @return
*/
private static StrategyConfig initStrategyConfig(String tableName, String... tablePrefix) {
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setTablePrefix(tablePrefix);
strategy.setInclude(tableName);
strategy.setRestControllerStyle(true);
return strategy;
}
/**
* 覆蓋Entity以及xml
*
* @param mapperFile
* @return
*/
private static TemplateConfig initTemplateConfig(String mapperFile) {
TemplateConfig tc = new TemplateConfig();
tc.setXml(null);
//如果當前Entity已經存在,那麼僅僅覆蓋Entity
File file = new File(mapperFile);
if (file.exists()) {
tc.setController(null);
tc.setMapper(null);
tc.setService(null);
tc.setServiceImpl(null);
tc.setEntityKt(null);
}
return tc;
}
public static class JdbcRepository {
private static Pattern linePattern = Pattern.compile("_(\\w)");
private JdbcOperations jdbcOperations;
public JdbcRepository() {
DataSource dataSource = DataSourceBuilder.create()
//如果不指定類型,那麼默認使用連接池,會存在連接不能回收而最終被耗盡的問題
.type(DriverManagerDataSource.class)
.driverClassName(driverName)
.url(url)
.username(userName)
.password(password)
.build();
this.jdbcOperations = new JdbcTemplate(dataSource);
}
/**
* 獲取所有實體類的名字,實體類由數據庫表名轉換而來.
* 例如: 表前綴爲auth,完整表名爲auth_first_second,那麼entity則爲FirstSecond
*
* @param tables 表名稱數據
* @param tablePrefixArray 數據庫表名前綴,可能爲空
* @return
*/
public Map<String, String> getEntityNames(List<String> tables, String... tablePrefixArray) {
//該sql語句目前支持mysql
String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '" + database + "'";
if (tablePrefixArray != null && tablePrefixArray.length != 0) {
sql += " and (";
for (String prefix : tablePrefixArray) {
sql += " or table_name like '" + prefix + "_%'";
}
sql += ")";
}
sql = sql.replaceFirst("or", "");
List<String> tableNames = jdbcOperations.query(sql, SingleColumnRowMapper.newInstance(String.class));
if (CollectionUtils.isEmpty(tableNames)) {
return new HashMap<>();
}
Map<String, String> result = new HashMap<>();
tableNames.forEach(
tableName -> {
// 如果指定具體的表名稱集合,則只生成匹配指定的集合
if (!CollectionUtils.isEmpty(tables)) {
if (tables.indexOf(tableName) == -1) {
return;
}
}
String entityName = underlineToCamel(tableName);
if (tablePrefixArray != null && tablePrefixArray.length != 0) {
for (String prefix : tablePrefixArray) {
//如果有前綴,需要去掉前綴
if (tableName.startsWith(prefix)) {
String tableNameRemovePrefix = tableName.substring((prefix + "_").length());
entityName = underlineToCamel(tableNameRemovePrefix);
}
}
}
result.put(tableName, entityName);
}
);
return result;
}
/**
* 下劃線轉駝峯
*
* @param str
* @return
*/
private static String underlineToCamel(String str) {
if (null == str || "".equals(str)) {
return str;
}
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
str = sb.toString();
str = str.substring(0, 1).toUpperCase() + str.substring(1);
return str;
}
}
}