SpringBoot+MybatisPlus+MySql 自动生成代码 自动分页
一、配置
<!-- Mybatis plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<!-- 自动生成代码 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.1</version>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
二、生成代码类
package com.czhappy.wanmathapi.generate; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.VelocityTemplateEngine;
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 javax.sql.DataSource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; public class MysqlGenerator { private static final String database = "wanmath";
private static final String url = "jdbc:mysql://localhost:3306/" + database
+ "?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC";
private static final String driverName = "com.mysql.jdbc.Driver";
private static final String userName = "root";
private static final String password = "root"; private static String basePath = "";
private static String mapperPath = ""; public static void main(String[] args) {
//生成代码,多张表用逗号分隔
generate("chenzheng","com.czhappy.wanmathapi", "tb_web_user");
} /**
* 自动生成代码
* @param author 作者
* @param packageName 包名
* @param tableNames 表
*/
public static void generate(String author, String packageName, String... tableNames) { // 全局配置
GlobalConfig gc = initGlobalConfig(author, packageName);
// 数据源配置
DataSourceConfig dsc = initDataSourceConfig();
// 包配置
PackageConfig pc = new PackageConfig().setParent(packageName);
// 模板引擎配置
VelocityTemplateEngine templateEngine = new VelocityTemplateEngine(); //每一个entity都需要单独设置InjectionConfig, StrategyConfig和TemplateConfig
Map<String, String> names = new JdbcRepository().getEntityNames(tableNames);
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);
mpg.setStrategy(strategy); // 模板配置
// mapper文件
String mapperFile = mapperPath
+ "/" + names.get(tableName) + "Mapper" + StringPool.DOT_XML;
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 = MysqlGenerator.class.getResource("").getPath();
String codeDir = tmp.substring(0, tmp.indexOf("/target"));
basePath = codeDir + "/src/main/java";
mapperPath = codeDir + "/src/main/resources/mapper";
System.out.println("basePath = " + basePath + "\nmapperPath = " + mapperPath);
gc.setOutputDir(basePath);
gc.setAuthor(author);
gc.setOpen(false);
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.vm") {
@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) {
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
//strategy.setTablePrefix("tb");
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);
System.out.println("file.exists()="+file.exists());
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 tableNameArray 数据库表名,可能为空
* @return
*/
public Map<String, String> getEntityNames(String... tableNameArray) {
//该sql语句目前支持mysql
String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '" + database + "'";
if (tableNameArray != null && tableNameArray.length != 0) {
sql += " and (";
for (String name : tableNameArray) {
sql += " or table_name = '" + name + "'";
}
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 -> {
String entityName = underlineToCamel(tableName);
// String prefix = "tb";
// //如果有前缀,需要去掉前缀
// if (tableName.startsWith(prefix)) {
// String tableNameRemovePrefix = tableName.substring((prefix + "_").length());
// entityName = underlineToCamel(tableNameRemovePrefix);
// System.out.println("******"+entityName+"******");
// } 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;
} }
}
SpringBoot+MybatisPlus+MySql 自动生成代码 自动分页的更多相关文章
- SpringBoot+Mybatis+MySql 自动生成代码 自动分页
一.配置文件 <!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <arti ...
- springboot 使用mybatis-generator自动生成代码
这里只介绍mybatis generator生成代码 一.pom配置 在build-->plugins-->添加plugin <plugin> <groupId>o ...
- springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)
这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...
- SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件
原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...
- SpringBoot 添加mybatis generator 自动生成代码插件
自动生成数据层代码,提高开发效率 1.pom添加插件,并指定配置文件路径 <!-- mybatis generator 自动生成代码插件 --> <plugin> <gr ...
- springboot mybatis 自动生成代码(maven+IntelliJ IDEA)
1.在pom文件中加入需要的依赖(mybatis-generator-core) 和 插件(mybatis-generator-maven-plugin) <dependency> < ...
- 一分钟带你学会利用mybatis-generator自动生成代码!
目录 一.MyBatis Generator简介 二.使用方式 三.实战 之前的文章<SpringBoot系列-整合Mybatis(XML配置方式)>介绍了XML配置方式整合的过程,本文介 ...
- mybatis自动生成代码插件mybatis-generator使用流程(亲测可用)
mybatis-generator是一款在使用mybatis框架时,自动生成model,dao和mapper的工具,很大程度上减少了业务开发人员的手动编码时间 坐着在idea上用maven构建spri ...
- mybatis generator maven插件自动生成代码
如果你正为无聊Dao代码的编写感到苦恼,如果你正为怕一个单词拼错导致Dao操作失败而感到苦恼,那么就可以考虑一些Mybatis generator这个差价,它会帮我们自动生成代码,类似于Hiberna ...
随机推荐
- Python开发应用-正则表达进行排序搜索
re模块提供了3个方法对输入的字符串进行确切的查询,match和search最多只会返回一个匹配条件的子串,可以理解为非贪婪模式,而findall会返回N个匹配条件的子串,可以理解为贪婪模式 re.m ...
- BZOJ-1975: 魔法猪学院 (K短路:A*+SPFA)
题意:有N种化学元素,有M种转化关系,(u,v,L)表示化学物质由u变为v需要L能量,现在你有E能量,问最多有多少种不同的途径,使得1转为为N,且总能量不超过E. 思路:可以转为为带权有向图,即是求前 ...
- WORD添加批注(JAVA)
import com.spire.doc.*;import com.spire.doc.documents.CommentMark;import com.spire.doc.documents.Com ...
- mysql数据库的concat(),group_concat(),concat_ws()函数,三者之间的比较
今天在写项目的时候,看到同事使用group_concat()函数 和concat_ws()函数,这两个函数和普通的concat()函数之间到底有什么不同. 我使用的数据库是mysql数据库. GROU ...
- noip初赛试题
链接: https://pan.baidu.com/s/1yoOMIUqMRBnBUPprC3o6HQ&shfl=shareset 提取码: m8ns 复制这段内容后打开百度网盘手机App,操 ...
- 《三体》刘慈欣英文演讲:说好的星辰大海你却只给了我Facebook
美国当地时间2018日11月8日,著名科幻作家刘慈欣被授予2018年度克拉克想象力贡献社会奖(Clarke Award for Imagination in Service to Society),表 ...
- Gift to XBACK(小小礼物)
什么白天 什么黑夜 我没有 准备着给你的 Surprise 你给我的爱 让我觉得已足够 是你让我相信爱会有 是你的爱陪我绕宇宙 打开日记本写下忧愁 你却让我看时间轴 我才知道现在我能看到的画面 拥有你 ...
- 洛谷P4408 逃学的小孩
题目 求树的直径,因为任意两个居住点之间有且只有一条通路,所以这是一棵树. 根据题意父母先从C去A,再去B,或者反过来. 我们一定是要让A到B最大,也要让C到A和B的最小值最大. AB最大一定就是直径 ...
- IDEA的foreach循环
试了试其他快捷键, 突然发现的... 先弄一个list 再把变量名写出来先 按快捷键 ctrl+alt+J, 选最后一个 看效果
- 【04NOIP普及组】火星人(信息学奥赛一本通 1929)(洛谷 1088)
[题目描述] 人类终于登上了火星的土地并且见到了神秘的火星人.人类和火星人都无法理解对方的语言,但是我们的科学家发明了一种用数字交流的方法.这种交流方法是这样的,首先,火星人把一个非常大的数字告诉人类 ...