今天在我的开源项目中增加了代码生成器,以及优化了目录结构。持久层升级为mybatisplus。下面说说我们如何集成代码生成器。
目录结构如下:
第一步:增加pom文件依赖:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!-- mybatis plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> <version>2.3.5.RELEASE</version> </dependency> <!-- 模板引擎 --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency> |
第二步:新建GeneratorCodeConfig
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package com.plugin.mybatisgenerator; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.plugin.mybatisgenerator.util.CommonUtils; import org.apache.commons.lang3.StringUtils; import java.util.Scanner; /** * 自动生成mybatisplus的相关代码 */ public class GeneratorCodeConfig { public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } public static void main(String[] args) { DbType dbType = DbType.MYSQL; String dbUrl = "jdbc:mysql://127.0.0.1:3306/xiwen?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&allowPublicKeyRetrieval=true"; String username = "root"; String password = "123456"; String driver = "com.mysql.jdbc.Driver"; // 表名,为空,生成所有的表 String [] tableNames = {}; tableNames = scanner("表名,多个英文逗号分割").split(","); // 表前缀,生成的实体类,不含前缀 String [] tablePrefixes = {}; // 字段前缀 String [] fieldPrefixes = {}; // 排除的表名 String [] excludeTableNames = {}; // 基础包名 String packageName = "com.xiwenzhang.test"; CommonUtils.execute(dbType, dbUrl, username, password, driver, tablePrefixes, tableNames, packageName, fieldPrefixes, excludeTableNames); } } |
第三步:新建CommonUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | package com.plugin.mybatisgenerator.util; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.annotation.IdType; 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.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine; import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine; import com.plugin.mybatisgenerator.config.Config; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.List; /** * @author Erwin Feng * @since 2019-04-17 12:04 */ public class CommonUtils { /** * 数据连接信息 * @param dbType 数据库类型 * @param dbUrl 连接地址 * @param username 用户名 * @param password 密码 * @param driver 驱动 * @return DataSourceConfig */ private static DataSourceConfig dataSourceConfig(DbType dbType, String dbUrl, String username, String password, String driver) { return new DataSourceConfig() .setDbType(dbType) .setUrl(dbUrl) .setUsername(username) .setPassword(password) .setDriverName(driver) ; } // 配置 private static GlobalConfig globalConfig() { return new GlobalConfig() .setAuthor(Config.AUTHOR) .setOutputDir(Config.OUTPUT_DIR) .setFileOverride(true) // 是否覆盖已有文件 .setOpen(true) // 是否打开输出目录 .setDateType(DateType.TIME_PACK) // 时间采用java 8,(操作工具类:JavaLib => DateTimeUtils) .setActiveRecord(true)// 不需要ActiveRecord特性的请改为false .setEnableCache(false)// XML 二级缓存 .setBaseResultMap(false)// XML ResultMap .setBaseColumnList(false)// XML columList .setKotlin(false) //是否生成 kotlin 代码 // 自定义文件命名,注意 %s 会自动填充表实体属性! .setEntityName(Config.FILE_NAME_MODEL) .setMapperName(Config.FILE_NAME_DAO) .setXmlName(Config.FILE_NAME_XML) .setServiceName(Config.FILE_NAME_SERVICE) .setServiceImplName(Config.FILE_NAME_SERVICE_IMPL) .setControllerName(Config.FILE_NAME_CONTROLLER) .setIdType(IdType.UUID) // 主键类型 .setSwagger2(Config.SWAGGER_SUPPORT); // model swagger2 } private static StrategyConfig strategyConfig(String [] tablePrefixes, String [] tableNames, String [] fieldPrefixes, String [] excludeTableNames) { StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig.setCapitalMode(true) ; // 全局大写命名 ORACLE 注意 strategyConfig.setSkipView(false) ; // 是否跳过视图 strategyConfig.setTablePrefix(tablePrefixes) ;// 此处可以修改为您的表前缀(数组) strategyConfig.setFieldPrefix(fieldPrefixes) ; // 字段前缀 strategyConfig.setNaming(NamingStrategy.underline_to_camel) ; // 表名生成策略 strategyConfig.setInclude(tableNames) ;//修改替换成你需要的表名,多个表名传数组 strategyConfig.setExclude(excludeTableNames) ; // 排除生成的表 strategyConfig.setEntityLombokModel(true) ; // lombok实体 strategyConfig.setEntityColumnConstant(false) ; // 【实体】是否生成字段常量(默认 false)// 可通过常量名获取数据库字段名 // 3.x支持lambda表达式 strategyConfig.setLogicDeleteFieldName(Config.FIELD_LOGIC_DELETE_NAME);// 逻辑删除属性名称 strategyConfig.setVersionFieldName(Config.FIELD_VERSION_NAME) ;// 乐观锁字段名 strategyConfig.setEntityTableFieldAnnotationEnable(true) ; // 开启实体字段注解 return strategyConfig; } // 包信息配置 private static PackageConfig packageConfig(String packageName) { return new PackageConfig() .setParent(packageName) .setController(Config.PACKAGE_NAME_CONTROLLER) .setEntity(Config.PACKAGE_NAME_MODEL) .setMapper(Config.PACKAGE_NAME_DAO) .setXml(Config.DIR_NAME_XML) .setService(Config.PACKAGE_NAME_SERVICE) .setServiceImpl(Config.PACKAGE_NAME_SERVICE_IMPL) ; } /** * @param packageConfig * @return */ private static InjectionConfig injectionConfig(final PackageConfig packageConfig) { InjectionConfig injectionConfig = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List<FileOutConfig> fileOutConfigList = new ArrayList<FileOutConfig>(); fileOutConfigList.add(new FileOutConfig("/templates/mapper.xml.ftl") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 if (StringUtils.isEmpty(packageConfig.getModuleName())) { return Config.PROJECT_PATH + "/src/main/resources/mapper/" + tableInfo.getXmlName() + StringPool.DOT_XML; }else { return Config.PROJECT_PATH + "/src/main/resources/mapper/" + packageConfig.getModuleName() + "/" + tableInfo.getXmlName() + StringPool.DOT_XML; } } }); injectionConfig.setFileOutConfigList(fileOutConfigList); return injectionConfig; } /** * 获取模板引擎 * @return 模板引擎 {@link AbstractTemplateEngine} */ private static AbstractTemplateEngine getTemplateEngine() { String templateEngine = Config.TEMPLATE_ENGINE; switch (templateEngine) { case "velocity": return new VelocityTemplateEngine(); case "freemarker": return new FreemarkerTemplateEngine(); case "beetl": return new BeetlTemplateEngine(); } return new VelocityTemplateEngine(); } /** * 执行器 */ public static void execute(DbType dbType, String dbUrl, String username, String password, String driver, String [] tablePrefixes, String [] tableNames, String packageName, String [] fieldPrefixes, String [] excludeTableNames) { GlobalConfig globalConfig = globalConfig(); DataSourceConfig dataSourceConfig = dataSourceConfig(dbType, dbUrl, username, password, driver); StrategyConfig strategyConfig = strategyConfig(tablePrefixes, tableNames, fieldPrefixes, excludeTableNames); PackageConfig packageConfig = packageConfig(packageName); // InjectionConfig injectionConfig = injectionConfig(packageConfig); AbstractTemplateEngine templateEngine = getTemplateEngine(); new AutoGenerator() .setGlobalConfig(globalConfig) .setDataSource(dataSourceConfig) .setStrategy(strategyConfig) .setPackageInfo(packageConfig) .setTemplateEngine(templateEngine) //.setCfg(injectionConfig) .execute(); } } |
第四步新建Config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | package com.plugin.mybatisgenerator.config; public class Config { /** 包名:controller */ public static final String PACKAGE_NAME_CONTROLLER = "controller"; /** 包名:service */ public static final String PACKAGE_NAME_SERVICE = "Service"; /** 包名:service.impl */ public static final String PACKAGE_NAME_SERVICE_IMPL = "Service.impl"; /** 包名:model */ public static final String PACKAGE_NAME_MODEL = "entity"; /** 包名:dao */ public static final String PACKAGE_NAME_DAO = "dao"; /** 目录名:xml */ public static final String DIR_NAME_XML = "mapper"; /** 文件名后缀:Model */ public static final String FILE_NAME_MODEL = "%sEntity"; /** 文件名后缀:Dao */ public static final String FILE_NAME_DAO = "%sDao"; /** 文件名后缀:Mapper */ public static final String FILE_NAME_XML = "%sMapper"; /** MP开头,Service结尾 */ public static final String FILE_NAME_SERVICE = "%sService"; /** 文件名后缀:ServiceImpl */ public static final String FILE_NAME_SERVICE_IMPL = "%sServiceImpl"; /** 文件名后缀:Controller */ public static final String FILE_NAME_CONTROLLER = "%sController"; /** 逻辑删除字段 */ public static final String FIELD_LOGIC_DELETE_NAME = "delete_status"; /** 乐观锁字段名 */ public static final String FIELD_VERSION_NAME = "version"; /** 作者 */ public static final String AUTHOR = "Xiwen"; /** 生成文件的输出目录 */ public static String PROJECT_PATH = System.getProperty("user.dir"); /** 输出目录 */ public static final String OUTPUT_DIR = PROJECT_PATH + "/src/main/java"; /** 模板引擎。velocity / freemarker / beetl */ public static final String TEMPLATE_ENGINE = "velocity"; /** 是否支持Swagger,默认不支持 */ public static final Boolean SWAGGER_SUPPORT = false; } |
然后我们开始测试,在数据库新建张表test然后运行GeneratorCodeConfig
输入表名回车:
ps:生成代只需要把GeneratorCodeConfig中的包名packageName和config中的 /** 输出目录 */换成你自己的就ok.
原文地址(含开源地址):http://www.xiwenblog.com/archives/3001?reload=true