一、配置

<!-- 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. 编程小白入门分享五:Vue的自定义组件

    前言 上篇博客简单介绍了vue,本篇博客要在对vue有一定了解后,才可以比较容易理解自定义组件.想要封装好一个组件,一定要熟练掌握这三个技能,父组件 -> 子组件传值(props).子组件 -& ...

  2. keyword (this and arguments) in function --- 涉及递归

    arguments 就像一个数组一样,包含了传递给这个函数的参数 , 以上部分为this的介绍,注意arguments.callee  属性 ,可用于递归调用,其代表的是  : 当前正在运行函数的引用 ...

  3. PHP——数组根据某一键值合并

    前言 其实要实现很简单直接foreach,再根据PHP中数组的特性就可以轻松实现. 步骤 这是源数据的格式 $info = [ [ "gname" => "特别关心 ...

  4. SQL操作Spark SQL--CatalogApiTest

    object CatalogApiTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() ...

  5. php读取外部txt文件内容并打印在页面|fopen()函数

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  6. May Cook-Off 2019 解题报告

    太气了.Atcoder unrated了. 这一场时间太不友好了.昨天下午一时兴起就去补了一发.题很好,学到好多东西. Chain Reaction 题意:给一个矩阵,这个矩阵是稳定的当且仅当每一个元 ...

  7. 【UVA11988】破损的键盘

    题目链接 维护一个链表,以及当前位置.head.tail的指针,模拟就行了 #include<iostream> #include<cstring> #include<c ...

  8. C博客作业03——函数

    0.展示PTA总分 截图展示: 1.本章学习总结 1.1学习内容总结 (a)函数的定义 1)函数是一个完成特定工作的独立程序模块,包括库函数和自定义函数两种,scanf(),printf()等为库函数 ...

  9. python学习笔记二:(python3 logging函数中format说明)

    背景,在学习logging时总是遇到无法理解的问题,总结,尝试一下更清晰明了了,让我们开始吧! logging模块常用format格式说明 %(levelno)s: 打印日志级别的数值 %(level ...

  10. last-child为啥不生效

    last-child基本定义 指定属于其父元素的最后一个子元素的 p 元素的背景色 如果你这样写是不会生效的 <div class="limit-border"> &l ...