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

一、配置

1<!-- Mybatis plus --> 2 <dependency> 3 <groupId>com.baomidou</groupId> 4 <artifactId>mybatis-plus-boot-starter</artifactId> 5 <version>3.1.1</version> 6 </dependency> 7 <!-- 自动生成代码 --> 8 <dependency> 9 <groupId>com.baomidou</groupId> 10 <artifactId>mybatis-plus-generator</artifactId> 11 <version>3.1.1</version> 12 </dependency> 13 <!-- 模板引擎 --> 14 <dependency> 15 <groupId>org.apache.velocity</groupId> 16 <artifactId>velocity-engine-core</artifactId> 17 <version>2.1</version> 18 </dependency> 19 <!-- lombok --> 20 <dependency> 21 <groupId>org.projectlombok</groupId> 22 <artifactId>lombok</artifactId> 23 <version>1.16.10</version> 24 </dependency>

二、生成代码类

1package com.czhappy.wanmathapi.generate; 2 3import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; 4import com.baomidou.mybatisplus.core.toolkit.StringPool; 5import com.baomidou.mybatisplus.generator.AutoGenerator; 6import com.baomidou.mybatisplus.generator.InjectionConfig; 7import com.baomidou.mybatisplus.generator.config.*; 8import com.baomidou.mybatisplus.generator.config.po.TableInfo; 9import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; 10import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine; 11import org.springframework.boot.jdbc.DataSourceBuilder; 12import org.springframework.jdbc.core.JdbcOperations; 13import org.springframework.jdbc.core.JdbcTemplate; 14import org.springframework.jdbc.core.SingleColumnRowMapper; 15import org.springframework.jdbc.datasource.DriverManagerDataSource; 16 17import javax.sql.DataSource; 18import java.io.File; 19import java.util.ArrayList; 20import java.util.HashMap; 21import java.util.List; 22import java.util.Map; 23import java.util.regex.Matcher; 24import java.util.regex.Pattern; 25 26public class MysqlGenerator { 27 28 private static final String database = "wanmath"; 29 private static final String url = "jdbc:mysql://localhost:3306/" + database 30 + "?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"; 31 private static final String driverName = "com.mysql.jdbc.Driver"; 32 private static final String userName = "root"; 33 private static final String password = "root"; 34 35 private static String basePath = ""; 36 private static String mapperPath = ""; 37 38 39 public static void main(String[] args) { 40 //生成代码,多张表用逗号分隔 41 generate("chenzheng","com.czhappy.wanmathapi", "tb_web_user"); 42 } 43 44 45 /** 46 * 自动生成代码 47 * @param author 作者 48 * @param packageName 包名 49 * @param tableNames50 */ 51 public static void generate(String author, String packageName, String... tableNames) { 52 53 // 全局配置 54 GlobalConfig gc = initGlobalConfig(author, packageName); 55 // 数据源配置 56 DataSourceConfig dsc = initDataSourceConfig(); 57 // 包配置 58 PackageConfig pc = new PackageConfig().setParent(packageName); 59 // 模板引擎配置 60 VelocityTemplateEngine templateEngine = new VelocityTemplateEngine(); 61 62 63 //每一个entity都需要单独设置InjectionConfig, StrategyConfig和TemplateConfig 64 Map<String, String> names = new JdbcRepository().getEntityNames(tableNames); 65 if (names == null || names.isEmpty()) { 66 return; 67 } 68 for (String tableName : names.keySet()) { 69 // 代码生成器 70 AutoGenerator mpg = new AutoGenerator(); 71 mpg.setGlobalConfig(gc); 72 mpg.setDataSource(dsc); 73 mpg.setPackageInfo(pc); 74 mpg.setTemplateEngine(templateEngine); 75 76 // 自定义配置 77 InjectionConfig cfg = initInjectionConfig(packageName); 78 mpg.setCfg(cfg); 79 80 // 策略配置 81 StrategyConfig strategy = initStrategyConfig(tableName); 82 mpg.setStrategy(strategy); 83 84 // 模板配置 85 // mapper文件 86 String mapperFile = mapperPath 87 + "/" + names.get(tableName) + "Mapper" + StringPool.DOT_XML; 88 TemplateConfig tc = initTemplateConfig(mapperFile); 89 mpg.setTemplate(tc); 90 91 //开始执行 92 mpg.execute(); 93 } 94 } 95 96 97 /** 98 * 配置数据源 99 * @return 100 */ 101 private static DataSourceConfig initDataSourceConfig() { 102 return new DataSourceConfig() 103 .setUrl(url) 104 .setDriverName(driverName) 105 .setUsername(userName) 106 .setPassword(password); 107 } 108 109 /** 110 * 全局配置 111 * @return 112 */ 113 private static GlobalConfig initGlobalConfig(String author, String packageName) { 114 GlobalConfig gc = new GlobalConfig(); 115 String tmp = MysqlGenerator.class.getResource("").getPath(); 116 String codeDir = tmp.substring(0, tmp.indexOf("/target")); 117 basePath = codeDir + "/src/main/java"; 118 mapperPath = codeDir + "/src/main/resources/mapper"; 119 System.out.println("basePath = " + basePath + "\nmapperPath = " + mapperPath); 120 gc.setOutputDir(basePath); 121 gc.setAuthor(author); 122 gc.setOpen(false); 123 gc.setServiceName("%sService"); 124 gc.setFileOverride(true); 125 126 return gc; 127 } 128 129 /** 130 * 自定义配置 131 * @param packageName 132 * @return 133 */ 134 private static InjectionConfig initInjectionConfig(String packageName) { 135 InjectionConfig cfg = new InjectionConfig() { 136 @Override 137 public void initMap() { 138 // to do nothing 139 } 140 }; 141 List<FileOutConfig> focList = new ArrayList<>(); 142 focList.add(new FileOutConfig("/templates/mapper.xml.vm") { 143 @Override 144 public String outputFile(TableInfo tableInfo) { 145 //自定义输入文件名称 146 return mapperPath 147 + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; 148 } 149 }); 150 cfg.setFileOutConfigList(focList); 151 152 return cfg; 153 } 154 155 /** 156 * 策略配置 157 * @param tableName 数据库表名 158 * @return 159 */ 160 private static StrategyConfig initStrategyConfig(String tableName) { 161 StrategyConfig strategy = new StrategyConfig(); 162 strategy.setNaming(NamingStrategy.underline_to_camel); 163 strategy.setColumnNaming(NamingStrategy.underline_to_camel); 164 strategy.setEntityLombokModel(true); 165 //strategy.setTablePrefix("tb"); 166 strategy.setInclude(tableName); 167 strategy.setRestControllerStyle(true); 168 169 return strategy; 170 } 171 172 /** 173 * 覆盖Entity以及xml 174 * @param mapperFile 175 * @return 176 */ 177 private static TemplateConfig initTemplateConfig(String mapperFile) { 178 TemplateConfig tc = new TemplateConfig(); 179 tc.setXml(null); 180 //如果当前Entity已经存在,那么仅仅覆盖Entity 181 File file = new File(mapperFile); 182 System.out.println("file.exists()="+file.exists()); 183 if (file.exists()) { 184 tc.setController(null); 185 tc.setMapper(null); 186 tc.setService(null); 187 tc.setServiceImpl(null); 188 tc.setEntityKt(null); 189 } 190 191 return tc; 192 } 193 194 195 196 public static class JdbcRepository { 197 private static Pattern linePattern = Pattern.compile("_(\\w)"); 198 private JdbcOperations jdbcOperations; 199 public JdbcRepository() { 200 DataSource dataSource = DataSourceBuilder.create() 201 //如果不指定类型,那么默认使用连接池,会存在连接不能回收而最终被耗尽的问题 202 .type(DriverManagerDataSource.class) 203 .driverClassName(driverName) 204 .url(url) 205 .username(userName) 206 .password(password) 207 .build(); 208 this.jdbcOperations = new JdbcTemplate(dataSource); 209 } 210 211 /** 212 * 获取所有实体类的名字,实体类由数据库表名转换而来. 213 * 例如: 表前缀为auth,完整表名为auth_first_second,那么entity则为FirstSecond 214 * @param tableNameArray 数据库表名,可能为空 215 * @return 216 */ 217 public Map<String, String> getEntityNames(String... tableNameArray) { 218 //该sql语句目前支持mysql 219 String sql = "SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '" + database + "'"; 220 if (tableNameArray != null && tableNameArray.length != 0) { 221 sql += " and ("; 222 for (String name : tableNameArray) { 223 sql += " or table_name = '" + name + "'"; 224 } 225 sql += ")"; 226 } 227 sql = sql.replaceFirst("or", ""); 228 List<String> tableNames = jdbcOperations.query(sql, SingleColumnRowMapper.newInstance(String.class)); 229 if (CollectionUtils.isEmpty(tableNames)) { 230 return new HashMap<>(); 231 } 232 233 234 Map<String, String> result = new HashMap<>(); 235 tableNames.forEach( 236 tableName -> { 237 String entityName = underlineToCamel(tableName); 238// String prefix = "tb"; 239// //如果有前缀,需要去掉前缀 240// if (tableName.startsWith(prefix)) { 241// String tableNameRemovePrefix = tableName.substring((prefix + "_").length()); 242// entityName = underlineToCamel(tableNameRemovePrefix); 243// System.out.println("******"+entityName+"******"); 244// } 245 246 result.put(tableName, entityName); 247 } 248 ); 249 250 251 return result; 252 } 253 254 255 /** 256 * 下划线转驼峰 257 * 258 * @param str 259 * @return 260 */ 261 private static String underlineToCamel(String str) { 262 if (null == str || "".equals(str)) { 263 return str; 264 } 265 str = str.toLowerCase(); 266 Matcher matcher = linePattern.matcher(str); 267 StringBuffer sb = new StringBuffer(); 268 while (matcher.find()) { 269 matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); 270 } 271 matcher.appendTail(sb); 272 273 str = sb.toString(); 274 str = str.substring(0, 1).toUpperCase() + str.substring(1); 275 276 return str; 277 } 278 279 } 280}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )