首页 > 数据库 >SpringBoot+MybatisPlus+MySql 自动生成代码 自动分页

SpringBoot+MybatisPlus+MySql 自动生成代码 自动分页

时间:2023-03-02 12:32:20浏览次数:47  
标签:return SpringBoot new static 自动 private import MybatisPlus String


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;
}

}
}



 







标签:return,SpringBoot,new,static,自动,private,import,MybatisPlus,String
From: https://blog.51cto.com/u_4427045/6095969

相关文章

  • Xmemcached与SpringBoot实际案例
    在本人的这篇文章《​​Xmemcached集群与SpringBoot整合​​》基础上,进行XMemcached与SpringBoot实际案例的结合。有以下这张表,将这张表的增删改查操作都添加到XMemcached中......
  • 通过手动创建hibernate工厂,自动生成表,完成数据库备份还原功能
    最近做toB、toG业务,普遍要去适配各种国产数据库,所以不得不用hibernate,过去这么多年一直都是用mybatis+mysql,现在重拾hibernate,专注跨数据库,感兴趣的加关注。需求背景:最近......
  • 使用gitlab+jenkins实现本地推送到仓库并且自动更新到线上
    1、安装好gitlab服务(不详细介绍)2、安装好jenkins服务(不详细介绍)gitlab配置在gitlab上进入要操作的项目,在左边的菜单栏上找到这个配置,【设置-Webhooks】 网址:从jenki......
  • springboot后端接收不到前端传来的表单值
    为啥接收不到因为传来的字段值太大了,springboot默认启动依赖tomcat,tomcat默认接收表单值最大为2MB,将server.tomcat.max-http-form-post-size这个配置调大即可#yml方式s......
  • 用例需注意的点-UI自动化
    记几条--用例注意事项:用例从功能里面转化而来,并且不能脱离业务(针对某一个页面功能\某一个流程业务,写一条用例:即将界面操作间接转化为代码去操作!)1用例要尽量独立,相互不影响!(......
  • 九、MybatisPlus的多数据源
    场景适用于多种场景:纯粹多库、读写分离、一主多从、混合模式等目前我们就来模拟一个纯粹多库的一个场景,其他场景类似场景说明:我们创建两个库,分别为:mybatis_plus(以前......
  • SpringBoot+WebSocket实现实时获取系统数据
    SpringBoot+WebSocket实现实时获取系统数据引入maven依赖<dependencies><dependency><groupId>org.springframework.boot</groupId>......
  • 八、MybatisPlus的代码生成器示例
    引入依赖<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.1</version></dependency><dependency> <......
  • Tek示波器自动化测试(PyVISA)
    1.相关资料1.1PyVISAPyVISA·PyPI1.1.1用户指南用户指南—PyVISA文档1.1.2要求Python(使用3.6+测试)VISA(使用NI-VISA17.5,Win7,下载NI-VISA-NI) 1.1.3实例......
  • AI自动生成prompt媲美人类,网友:工程师刚被聘用又要淘汰了
    机器之心报道机器之心编辑部来自多伦多大学、滑铁卢大学等机构的研究者受promptengineering的启发,提出一种使用大型语言模型自动生成和选择指令的新算法,在24项任务......