A configuration
<!-- 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>
Second, to generate the class codes
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) { // generated code, more than one table separated by commas Generate ( "chenzheng", "com.czhappy.wanmathapi", "tb_web_user" ); } / ** * automatically generate the code * @param author OF * @param the packageName package names * @param TableNames table * / public static void generate (String author, the packageName String, String TableNames ...) { // global configuration globalConfig gc =initGlobalConfig (author, the packageName); // data source configuration DataSourceConfig DSC = initDataSourceConfig (); // package configuration PackageConfig PC = new new PackageConfig () the setParent (the packageName);. // template engine configuration VelocityTemplateEngine TemplateEngine = new new VelocityTemplateEngine (); / / each entity requires a separate set InjectionConfig, StrategyConfig and TemplateConfig the Map <String, String> = names new new JdbcRepository () getEntityNames (TableNames);. IF (names == null || names.isEmpty ()) { return; } For (String tableName: names.keySet ()) { // code generator AutoGenerator MPG = new new AutoGenerator (); mpg.setGlobalConfig (GC); mpg.setDataSource (DSC); mpg.setPackageInfo (PC); MPG. setTemplateEngine (TemplateEngine); // custom configuration InjectionConfig cfg = initInjectionConfig (packageName); mpg.setCfg (cfg); // policy configuration StrategyConfig at strategy = initStrategyConfig (tableName); mpg.setStrategy (at strategy); // template configuration // Mapper file String mapperFile = mapperPath + "/" + names.get (tableName) + "Mapper" + StringPool.DOT_XML; TemplateConfig tc = initTemplateConfig (mapperFile); mpg.setTemplate (tc); // begin mpg.execute (); } } / ** * configuration data source * @return * / Private static DataSourceConfig initDataSourceConfig () { return new new DataSourceConfig () .setUrl (URL) .setDriverName (driverName) .setUsername (the 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 ( to true ); return Strategy; } / ** * Entity coverage and XML * @param mapperFile * @return * / Private static TemplateConfig initTemplateConfig (String mapperFile) { TemplateConfig TC = new new TemplateConfig (); tc.setXml ( null ); // If the current Entity already exists, it covers only Entity File File = new 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 the Pattern of Pattern.compile linePattern = ( "_ (\\ W)" ); Private jdbcOperations jdbcOperations; public JdbcRepository() { the dataSource dataSource = DataSourceBuilder.create () // If you do not specify a type, then use the default connection pool, there is a connection can not be recycled and will eventually run out of the question .Type (the DriverManagerDataSource. class ) .driverClassName (driverName) .url (URL) .username (the userName) .password (password) .build (); the this .jdbcOperations = new new the JdbcTemplate (the dataSource); } / ** * Get all entities class name, entity class converted from a database table names. * For example: table prefix auth, complete table named auth_first_second, then the entity was FIRST SECOND * @param tableNameArray database table names , may be empty * @return * / public the 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); // Prefix = String "TB"; // // If there is a prefix, the prefix need to remove // IF (tableName.startsWith (prefix)) { // String tableNameRemovePrefix tableName.substring = ((prefix + "_") length (). ); // the entityName = underlineToCamel (tableNameRemovePrefix); // System.out.println ( "******" the entityName + + "******"); // } result.put (tableName, the entityName) ; } ); return Result; } / ** * underlined turn hump * * @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; } } }