一、配置

<!-- 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 自动生成代码 自动分页的更多相关文章

  1. SpringBoot+Mybatis+MySql 自动生成代码 自动分页

    一.配置文件 <!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <arti ...

  2. springboot 使用mybatis-generator自动生成代码

    这里只介绍mybatis generator生成代码 一.pom配置 在build-->plugins-->添加plugin <plugin> <groupId>o ...

  3. springboot学习随笔(四):Springboot整合mybatis(含generator自动生成代码)

    这章我们将通过springboot整合mybatis来操作数据库 以下内容分为两部分,一部分主要介绍generator自动生成代码,生成model.dao层接口.dao接口对应的sql配置文件 第一部 ...

  4. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  5. SpringBoot 添加mybatis generator 自动生成代码插件

    自动生成数据层代码,提高开发效率 1.pom添加插件,并指定配置文件路径 <!-- mybatis generator 自动生成代码插件 --> <plugin> <gr ...

  6. springboot mybatis 自动生成代码(maven+IntelliJ IDEA)

    1.在pom文件中加入需要的依赖(mybatis-generator-core) 和 插件(mybatis-generator-maven-plugin) <dependency> < ...

  7. 一分钟带你学会利用mybatis-generator自动生成代码!

    目录 一.MyBatis Generator简介 二.使用方式 三.实战 之前的文章<SpringBoot系列-整合Mybatis(XML配置方式)>介绍了XML配置方式整合的过程,本文介 ...

  8. mybatis自动生成代码插件mybatis-generator使用流程(亲测可用)

    mybatis-generator是一款在使用mybatis框架时,自动生成model,dao和mapper的工具,很大程度上减少了业务开发人员的手动编码时间 坐着在idea上用maven构建spri ...

  9. mybatis generator maven插件自动生成代码

    如果你正为无聊Dao代码的编写感到苦恼,如果你正为怕一个单词拼错导致Dao操作失败而感到苦恼,那么就可以考虑一些Mybatis generator这个差价,它会帮我们自动生成代码,类似于Hiberna ...

随机推荐

  1. Thinkphp下实现D函数用于实例化Model格式

    * D函数用于实例化Model 格式 项目://分组/模块 * @param string $name Model资源地址 * @param string $layer 业务层名称 * @return ...

  2. 洛谷:P1783 海滩防御(二分+并查集 最短路 最小生成树)

    题意: 给定长度为N的海滩,然后有M做防御塔,给出每座塔的位置Xi,到海岸的距离Yi. 求防御塔上最小观测半径Ri,使得海滩被封锁. 思路:要使左边界和右边界连通. 很nice,可以二分+并查集做. ...

  3. EntityFramework6 学习笔记(二)

    使用EF对数据库进行操作,整个过程就像操作数组一样,我们只管修改或向集合中添加值,最后通知EF保存修改后的结果就可以了. 准备工作 为了演示,我在数据库中建了两张表.class表用于表示班级,clas ...

  4. oracle数据库登录和

    首先引用百度云两个DLL文件 dbhelpher.DLL 和  Oracle.ManagedDataAccess.dll,加入配置文件sysdb文件 配置文件内容 < [DBMODE]MODE= ...

  5. 雅克比(Jacobi)方法

    可以用来求解协方差矩阵的特征值和特征向量. 雅可比方法(Jacobian method)求全积分的一种方法,把拉格朗阶查皮特方法推广到求n个自变量一阶非线性方程的全积分的方法称为雅可比方法. 雅克比迭 ...

  6. Lightning Web Components html_templates(三)

    Lightning Web Components 强大之处在于模版系统,使用了虚拟dom 进行智能高效的组件渲染. 使用简单语法以声明方式将组件的模板绑定到组件的JavaScript类中的数据 数据绑 ...

  7. NOI 2019 游记

    day -1 去报了个到,顺便买了一大堆衣服. 感觉学校饭堂不太行. day 0 上午是开幕式,. 下午是笔试,顺利获得 \(100\) 分. day 1 先看题. 第一题看到 \(At^2+Bt+C ...

  8. 一篇文章了解Github和Git教程

    有趣有内涵的文章第一时间送达! 喝酒I创作I分享 关注我,每天都有优质技术文章推送,工作,学习累了的时候放松一下自己. 本篇文章同步微信公众号 欢迎大家关注我的微信公众号:「醉翁猫咪」 生活中总有些东 ...

  9. IDEA实现SpringBoot热部署

    1.pom.xml添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifac ...

  10. LDAP -- ldap 的cn, ou, dc的含义

    1. LDAP的存储规则 区分名(DN,Distinguished Name) 和自然界中的树不同,文件系统/LDAP/电话号码簿目录的每一片枝叶都至少有一个独一无二的属性,这一属性可以帮助我们来区别 ...