diff --git a/.gitignore b/.gitignore index 52f86e1a00f01429651191077f152f9f2db2438a..e0a6df3e0f736022557664dbf1a322b2748e08b5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,9 @@ -/target/ -/.idea/ -/.gitignore -/.project -/mybatisplus-maven-plugin.iml -/.settings/ -/.classpath +# Java +target/ +logs/ +*.class +# Intellij IDEA +.idea +*.iws +*.iml +*.ipr \ No newline at end of file diff --git a/.project b/.project deleted file mode 100644 index 1b6712dd61718ab69adccda4aec5fea4d2495aaf..0000000000000000000000000000000000000000 --- a/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - mybatisplus-maven-plugin - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/README.md b/README.md index c0f337fb75b9f7e7b3f43bcb4104a8bc259d7f82..e639aff5abb16e95ce53eba4bc06b92fe989f06c 100644 --- a/README.md +++ b/README.md @@ -9,72 +9,51 @@ * 在项目的pom文件中配置以下内容 ```xml + com.baomidou mybatisplus-maven-plugin - 1.0 + 2.11 - - ${project.basedir}/src/main/java - - true - - false - - chenmin - - false - - com.mysql.cj.jdbc.Driver - jdbc:mysql://127.0.0.1:3306/test - root - root - - - - remove_underline_and_camel - underline_to_camel - - tb_ - - assign_id - - com.baomidou.mybatisplus.core.mapper.BaseMapper - com.baomidou.mybatisplus.extension.service.IService - com.baomidou.mybatisplus.extension.service.impl.ServiceImpl - - - - com.test - - service.interfaces - - service.impl - - bean - - mapper - - ${project.basedir}/src/main/resources/mapper - controller - - + + + db type + db hostname or ip + db port + db schema + db username + db password + + + + tp_app,tp_app_channel,tp_role,tp_role_permission,tp_user_role,tp_user_action_record + + tp_ + + + + + + + + + + id,description,status,create_time,update_time,created_by,updated_by + + + + com.unionnet.permission + com.unionnet.permission.basis.BasisEntity + + daixinjie + - mysql - mysql-connector-java - 8.0.19 + com.microsoft.sqlserver + mssql-jdbc + 12.4.2.jre8 @@ -85,7 +64,7 @@ 下载源码的同学!可使用mvn clean install将自定义的这个插件安装到本地仓库。 执行:`mvn clean install` -命令:`mvn com.baomidou:mybatisplus-maven-plugin:1.0:code` +命令:`mvn mybatisplus:generate` 显然这个命令太长了,使用很不方便,可在settings.xml中配置如下: @@ -94,5 +73,5 @@ com.baomidou ``` -然后使用简单命令:`mvn mp:code` +然后使用简单命令:`mvn mybatisplus:generate` diff --git a/pom.xml b/pom.xml index 6b8c026bb1bf537b8714eba9894cf3d150bc04c1..9b64b996c01db642934cc722c3c3d3fce39da0ba 100644 --- a/pom.xml +++ b/pom.xml @@ -1,267 +1,180 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.baomidou - mybatisplus-maven-plugin - 1.0 - maven-plugin + com.baomidou + mybatisplus-maven-plugin + 2.14 + maven-plugin - mybatisplus-maven-plugin Maven Plugin + Mybatis Plus Code Generator Plugin - https://github.com/baomidou/mybatisplus-maven-plugin - - - YangHu - althyman@gmail.com - baomidou - - - Mybatis-Plus Code Generator + https://github.com/baomidou/mybatisplus-maven-plugin + + + YangHu + althyman@gmail.com + baomidou + + + Mybatis-Plus Code Generator - - scm:git:git@git.oschina.net/baomidou/mybatisplus-maven-plugin.git - scm:git:git@git.oschina.net/baomidou/mybatisplus-maven-plugin.git - git@git.oschina.net/baomidou/mybatisplus-maven-plugin.git - + + scm:git:git@git.oschina.net/baomidou/mybatisplus-maven-plugin.git + scm:git:git@git.oschina.net/baomidou/mybatisplus-maven-plugin.git + git@git.oschina.net/baomidou/mybatisplus-maven-plugin.git + - - - Apache License Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 - - + + + Apache License Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + - - UTF-8 - F4B46FB9 - 8 - 8 - + + UTF-8 + F4B46FB9 + 8 + 8 + 3.5.2 + 3.5.2 + 3.5.5 + 3.5.5 + 2.3 + 2.3.31 + 3.15.10.RELEASE + 1.18.24 + 3.3.0 + 31.0.1-jre + - - - org.apache.maven - maven-plugin-api - 2.0 - - - org.apache.maven.plugin-tools - maven-plugin-annotations - 3.2 - provided - - - org.codehaus.plexus - plexus-utils - 3.0.8 - - - junit - junit - 4.8.2 - test - - - org.apache.velocity - velocity - 1.7 - - - mysql - mysql-connector-java - 5.1.38 - - + + + org.apache.maven + maven-plugin-api + ${maven-plugin-api.version} + + + org.apache.maven.plugin-tools + maven-plugin-annotations + ${maven-plugin-annotations.version} + provided + + + + com.baomidou + mybatis-plus-generator + ${mybatis-plus-generator.version} + + + com.baomidou + mybatis-plus + ${mybatis-plus.version} + + + org.apache.velocity + velocity-engine-core + ${velocity.version} + + + org.freemarker + freemarker + ${freemarker.version} + + + com.ibeetl + beetl + ${beetl.version} + + + org.projectlombok + lombok + ${lombok.verison} + + + cglib + cglib + ${cglib.version} + + + com.google.guava + guava + ${guava.version} + + - - - - ${project.basedir}/src/main/resources - - **/*.vm - - ${project.build.outputDirectory} - - - - - org.apache.maven.plugins - maven-plugin-plugin - 3.2 - - mp - true - - - - generated-helpmojo - - helpmojo - - - - + + + + ${project.basedir}/src/main/resources + + **/*.vm + + ${project.build.outputDirectory} + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.2.1 + + + org.apache.maven.plugins + maven-deploy-plugin + 3.1.1 + + + - - com.baomidou - mybatisplus-maven-plugin - 1.0 - - - C:\Users\Administrator\Desktop\mytest - - true - - true - - false - - tangguo - - false - - - - - - - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/mybatis-plus - root - 521 - - - - remove_prefix_and_camel - - bmd_ - - uuid - - - - - - - - - - - - - - - com.baomidou - - service - - service.impl - - entity - - mapper - - mapper.xml - - - - - - mysql - mysql-connector-java - 5.1.38 - - - - - - - - + + + org.apache.maven.plugins + maven-plugin-plugin + 3.5.2 + + mybatisplus + true + + + + org.apache.maven.plugins + maven-source-plugin + + + + attach-sources + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-deploy-plugin + + + deploy + + deploy + + + + + + + + + unionnet-releases + http://172.16.4.219:8094/repository/maven-releases/ + + + unionnet-snapshots + http://172.16.4.219:8094/repository/maven-snapshots/ + + - - - - - - release - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - package - - jar-no-fork - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - package - - jar - - - -Xdoclint:none - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - verify - - sign - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.19.1 - - true - - - - - - - oss - https://oss.sonatype.org/content/repositories/snapshots/ - - - oss - https://oss.sonatype.org/service/local/staging/deploy/maven2/ - - - - diff --git a/src/main/java/com/baomidou/AbstractGenerateMojo.java b/src/main/java/com/baomidou/AbstractGenerateMojo.java deleted file mode 100644 index 3e1ee246b102a386d0c0398abe03d7c8686f7ac9..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/AbstractGenerateMojo.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.baomidou; - -import com.baomidou.config.DataSourceConfig; -import com.baomidou.config.PackageConfig; -import com.baomidou.config.StrategyConfig; -import com.baomidou.config.TemplateConfig; -import com.baomidou.config.builder.ConfigBuilder; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugins.annotations.Parameter; - -/** - * 插件基类,用于属性配置 设计成抽象类主要是用于后期可扩展,共享参数配置。 - * - * @author YangHu - * @since 2016/8/30 - */ -public abstract class AbstractGenerateMojo extends AbstractMojo { - - /** - * 数据源配置 - */ - @Parameter(required = true) - private DataSourceConfig dataSource; - - /** - * 数据库表配置 - */ - @Parameter - private StrategyConfig strategy; - - /** - * 包 相关配置 - */ - @Parameter - private PackageConfig packageInfo; - - /** - * 模板 相关配置 - */ - @Parameter - private TemplateConfig template; - - /** - * 生成文件的输出目录 - */ - @Parameter - private String outputDir; - - /** - * 是否覆盖已有文件 - */ - @Parameter(defaultValue = "false") - private boolean fileOverride; - - /** - * 是否打开输出目录 - */ - @Parameter(defaultValue = "true") - private boolean open; - - /** - * 是否在xml中添加二级缓存配置 - */ - @Parameter(defaultValue = "true") - private boolean enableCache; - - /** - * 开发人员 - */ - @Parameter(defaultValue = "author") - private String author; - - /** - * 开启 ActiveRecord 模式 - */ - @Parameter(defaultValue = "true") - private boolean activeRecord; - - /** - * 开启 ActiveRecord 模式 - */ - @Parameter(defaultValue = "false") - private boolean enableSwagger; - - protected ConfigBuilder config; - - /** - * 日志工具 - */ - protected Log log = getLog(); - - /** - * 初始化配置 - */ - protected void initConfig() { - if (null == config) { - config = new ConfigBuilder(packageInfo, dataSource, strategy, template, outputDir); - } - } - - public String getOutputDir() { - return outputDir; - } - - public String getAuthor() { - return author; - } - - public boolean isFileOverride() { - return fileOverride; - } - - public boolean isOpen() { - return open; - } - - public boolean isEnableCache() { - return enableCache; - } - - public boolean isActiveRecord() { - return activeRecord; - } - - public boolean isEnableSwagger() { - return enableSwagger; - } - -} diff --git a/src/main/java/com/baomidou/Constants.java b/src/main/java/com/baomidou/Constants.java new file mode 100644 index 0000000000000000000000000000000000000000..db4c747b39124febe74df80baa3cd62eef47a96f --- /dev/null +++ b/src/main/java/com/baomidou/Constants.java @@ -0,0 +1,36 @@ +package com.baomidou; + +/** + * 定义常量 + * + * @author YangHu, tangguo + * @since 2016/8/31 + */ +public interface Constants { + // 目录配置 + String PACKAGE_ENTITY = "entity"; + String PACKAGE_MAPPER = "mapper"; + String PACKAGE_SERVICE = "service"; + String PACKAGE_SERVICE_IMPL = "service.impl"; + String PACKAGE_CONTROLLER = "controller"; + + // 文件名配置 + String FILENAME_ENTITY = "%s"; + String FILENAME_SERVICE = "%sService"; + String FILENAME_SERVICE_IMPL = "%sServiceImpl"; + String FILENAME_MAPPER = "%sMapper"; + String FILENAME_XML = "%s"; + String FILENAME_CONTROLLER = "%sController"; + + // 模板位置配置 + String TEMPLATE_ENTITY = "/template/entity.java.vm"; + String TEMPLATE_MAPPER = "/template/mapper.java.vm"; + String TEMPLATE_XML = "/template/mapper.xml.vm"; + String TEMPLATE_SERVICE = "/template/service.java.vm"; + String TEMPLATE_SERVICE_IMPL = "/template/serviceImpl.java.vm"; + String TEMPLATE_CONTROLLER = "/template/controller.java.vm"; + + String DEFAULT_JAVA_OUTPUT_DIR = "src/main/java"; + String DEFAULT_XML_OUTPUT_DIR = "src/main/resources/mapper"; + +} diff --git a/src/main/java/com/baomidou/CustomizedMSSQLTypeHandler.java b/src/main/java/com/baomidou/CustomizedMSSQLTypeHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..4471b4dc0ab1f5800db8c78e7a8b13c4f1557526 --- /dev/null +++ b/src/main/java/com/baomidou/CustomizedMSSQLTypeHandler.java @@ -0,0 +1,26 @@ +package com.baomidou; + +import com.baomidou.mybatisplus.generator.config.GlobalConfig; +import com.baomidou.mybatisplus.generator.config.po.TableField; +import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; +import com.baomidou.mybatisplus.generator.config.rules.IColumnType; +import com.baomidou.mybatisplus.generator.type.ITypeConvertHandler; +import com.baomidou.mybatisplus.generator.type.TypeRegistry; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.type.JdbcType; + +@Slf4j +public class CustomizedMSSQLTypeHandler implements ITypeConvertHandler { + @Override + public IColumnType convert(GlobalConfig globalConfig, + TypeRegistry typeRegistry, + TableField.MetaInfo metaInfo) { + if (JdbcType.BIT.equals(metaInfo.getJdbcType()) + || JdbcType.TINYINT.equals(metaInfo.getJdbcType()) + || JdbcType.SMALLINT.equals(metaInfo.getJdbcType()) + || JdbcType.BOOLEAN.equals(metaInfo.getJdbcType())) { + return DbColumnType.INTEGER; + } + return typeRegistry.getColumnType(metaInfo); + } +} \ No newline at end of file diff --git a/src/main/java/com/baomidou/GCPConfig.java b/src/main/java/com/baomidou/GCPConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..f6c2b0892a9af68d58792dad26440c4bd934b5a7 --- /dev/null +++ b/src/main/java/com/baomidou/GCPConfig.java @@ -0,0 +1,60 @@ +package com.baomidou; + +import com.baomidou.mybatisplus.annotation.DbType; +import lombok.Data; + +@Data +public class GCPConfig { + // 数据库类型 + private DbType dbType; + // 数据库连接hostname或ip + private String hostname; + // 数据库连接端口号 + private Integer port; + // 数据库连接数据库 + private String schema; + // 数据库名称 + private String username; + // 数据库密码 + private String password; + // 数据库连接地址 + private String dbUrl; + // 数据库驱动 + private String driver; + + // 表名 + private String[] includeTables; + // 排出表的表名 + private String[] excludeTables; + // 表前缀 + private String[] tablePrefixes; + // 表后缀 + private String[] tableSuffixes; + // 字段前缀 + private String[] fieldPrefixes; + // 字段后缀 + private String[] fieldSuffixes; + // 忽略的字段 + private String[] ignoreColumns; + + // 包名 + private String rootPackage; + + // 作者 + private String author; + + // 逻辑删除字段 + private String fieldLogicDelete; + + // 乐观锁字段 + private String fieldVersion; + + // 模版引擎 + private String templateEngine; + + // 实体父类的全类名 + private String superClassName; + + // ServiceImpl父类的全类名 + private String superServiceImplClass; +} diff --git a/src/main/java/com/baomidou/GCPGenerator.java b/src/main/java/com/baomidou/GCPGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..976829203a4fa63f8c115f0a6dd351929b6fde6f --- /dev/null +++ b/src/main/java/com/baomidou/GCPGenerator.java @@ -0,0 +1,134 @@ +package com.baomidou; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.generator.FastAutoGenerator; +import com.baomidou.mybatisplus.generator.config.*; +import com.baomidou.mybatisplus.generator.config.builder.Controller; +import com.baomidou.mybatisplus.generator.config.builder.Entity; +import com.baomidou.mybatisplus.generator.config.builder.Mapper; +import com.baomidou.mybatisplus.generator.config.builder.Service; +import com.baomidou.mybatisplus.generator.config.rules.DateType; +import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; +import com.google.common.base.Strings; + +import java.util.Collections; + +public class GCPGenerator { + + private final GCPConfig gcpConfig; + + public GCPGenerator(GCPConfig gcpConfig) { + this.gcpConfig = gcpConfig; + } + + public void execute() { + FastAutoGenerator.create(datasourceBuilder()) + .globalConfig(this::globalConfigBuilder) + .packageConfig(this::packageConfigBuilder) + .strategyConfig(this::strategyConfigBuilder) + .templateConfig(this::templateConfigBuilder) + .execute(); + } + + public DataSourceConfig.Builder datasourceBuilder() { + return new DataSourceConfig.Builder(gcpConfig.getDbUrl(), gcpConfig.getUsername(), gcpConfig.getPassword()) + .typeConvertHandler(new CustomizedMSSQLTypeHandler()); + } + + public void globalConfigBuilder(GlobalConfig.Builder builder) { + builder.outputDir(Constants.DEFAULT_JAVA_OUTPUT_DIR) + .author(gcpConfig.getAuthor()) + // 只支持jdk8 + .dateType(DateType.TIME_PACK) + // 不要打开代码生成目录 + .disableOpenDir(); + } + + public void packageConfigBuilder(PackageConfig.Builder builder) { + builder + .parent(gcpConfig.getRootPackage()) + .entity(Constants.PACKAGE_ENTITY) + .mapper(Constants.PACKAGE_MAPPER) + .service(Constants.PACKAGE_SERVICE) + .serviceImpl(Constants.PACKAGE_SERVICE_IMPL) + .controller(Constants.PACKAGE_CONTROLLER) + .pathInfo(Collections.singletonMap(OutputFile.xml, Constants.DEFAULT_XML_OUTPUT_DIR)); + } + + public void strategyConfigBuilder(StrategyConfig.Builder builder) { + builder.addInclude(gcpConfig.getIncludeTables()) + .addExclude(gcpConfig.getExcludeTables()) + .addTablePrefix(gcpConfig.getTablePrefixes()) + .addTableSuffix(gcpConfig.getTableSuffixes()) + .addFieldPrefix(gcpConfig.getFieldPrefixes()) + .addFieldSuffix(gcpConfig.getFieldSuffixes()); + // 以下是Entity相关配置 + // 置灰的强制不启用 + Entity.Builder entityBuilder = builder.entityBuilder(); + // 自定义继承的Entity类全称或者自定义继承的Entity类全称,带包名 + entityBuilder.superClass(gcpConfig.getSuperClassName()) + // 禁用生成serialVersionUID + //.disableSerialVersionUID() + // 开启生成字段常量 + .enableColumnConstant() + // 开启链式模型 + .enableChainModel() + // 开启lombok模型 + .enableLombok() + // 开启Boolean类型字段移除is前缀 + //.enableRemoveIsPrefix() + // 开启生成实体时生成字段注解 + .enableTableFieldAnnotation() + // 开启 ActiveRecord 模式 + //.enableActiveRecord() + // 设置乐观锁数据库表字段名称 + .versionColumnName(gcpConfig.getFieldVersion()) + // 设置乐观锁实体属性字段名称 + //.versionPropertyName(String versionPropertyName) + // 逻辑删除数据库字段名称 + .logicDeleteColumnName(gcpConfig.getFieldLogicDelete()) + // 逻辑删除实体属性名称 + //.logicDeletePropertyName(String logicDeletePropertyName) + // 数据库表映射到实体的命名策略 + .naming(NamingStrategy.underline_to_camel) + // 数据库表字段映射到实体的命名策略 + .columnNaming(NamingStrategy.underline_to_camel) + // 添加父类公共字段 + //.addSuperEntityColumns(String... superEntityColumns) + // 添加忽略字段 + .addIgnoreColumns(gcpConfig.getIgnoreColumns()) + // 指定生成的主键的ID类型 + .idType(IdType.ASSIGN_ID) + .enableFileOverride() + // 格式化文件名称 + .formatFileName(Constants.FILENAME_ENTITY); + // 以下是mapper相关配置 + Mapper.Builder mapperBuilder = builder.mapperBuilder(); + mapperBuilder.enableBaseResultMap() + .enableBaseColumnList() + .enableMapperAnnotation() + .enableFileOverride() + .formatMapperFileName(Constants.FILENAME_MAPPER) + .formatXmlFileName(Constants.FILENAME_XML); + // 以下是service相关配置 + Service.Builder serviceBuilder = builder.serviceBuilder(); + serviceBuilder.enableFileOverride() + .formatServiceFileName(Constants.FILENAME_SERVICE) + .formatServiceImplFileName(Constants.FILENAME_SERVICE_IMPL); + if (!Strings.isNullOrEmpty(gcpConfig.getSuperServiceImplClass())) { + serviceBuilder.superServiceImplClass(gcpConfig.getSuperServiceImplClass()); + } + // 以下是controller相关配置 + Controller.Builder controllerBuilder = builder.controllerBuilder(); + controllerBuilder.enableFileOverride() + .enableRestStyle() + .enableHyphenStyle() + .formatFileName(Constants.FILENAME_CONTROLLER); + } + + public void templateConfigBuilder(TemplateConfig.Builder builder) { + builder.disable(TemplateType.CONTROLLER) + .controller(Constants.TEMPLATE_CONTROLLER) + .build(); + } +} diff --git a/src/main/java/com/baomidou/GCPMojo.java b/src/main/java/com/baomidou/GCPMojo.java new file mode 100644 index 0000000000000000000000000000000000000000..a6e5e4127360fa6a3cda660bcf4b0e7a4ea37fe1 --- /dev/null +++ b/src/main/java/com/baomidou/GCPMojo.java @@ -0,0 +1,104 @@ +package com.baomidou; + +import com.baomidou.config.GCPDatasourceConfig; +import com.baomidou.config.GCPGlobalConfig; +import com.baomidou.config.GCPTableConfig; +import com.baomidou.mybatisplus.annotation.DbType; +import com.google.common.base.Strings; +import net.sf.cglib.beans.BeanCopier; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; + +import java.util.ArrayList; +import java.util.List; + +@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES) +public class GCPMojo extends AbstractMojo { + @Parameter(required = true) + private GCPDatasourceConfig datasource; + + @Parameter + private GCPTableConfig tableConfig; + + @Parameter + private GCPGlobalConfig globalConfig; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + try { + new GCPGenerator(prepareConfig()).execute(); + } catch (Throwable e) { + getLog().error("execute encounter error.", e); + } + } + + private GCPConfig prepareConfig() { + GCPConfig config = new GCPConfig(); + BeanCopier beanCopier = BeanCopier.create(datasource.getClass(), config.getClass(), false); + beanCopier.copy(datasource, config, null); + initDb(config); + initTable(config, tableConfig); + beanCopier = BeanCopier.create(globalConfig.getClass(), config.getClass(), false); + beanCopier.copy(globalConfig, config, null); + return config; + } + + private void initTable(GCPConfig config, GCPTableConfig tableConfig) { + config.setIncludeTables(split(tableConfig.getIncludeTables())); + config.setExcludeTables(split(tableConfig.getExcludeTables())); + config.setTablePrefixes(split(tableConfig.getTablePrefixes())); + config.setTableSuffixes(split(tableConfig.getTableSuffixes())); + config.setFieldPrefixes(split(tableConfig.getFieldPrefixes())); + config.setFieldSuffixes(split(tableConfig.getFieldSuffixes())); + config.setIgnoreColumns(split(tableConfig.getIgnoreColumns())); + } + + private String[] split(String value) { + if (Strings.isNullOrEmpty(value)) { + return new String[]{}; + } + List valueList = new ArrayList<>(); + String[] values; + if (value.contains(",")) { + values = value.split(","); + } else if (value.contains("\n")) { + values = value.split("\n"); + } else { + values = value.split(" "); + } + for (String str : values) { + str = str.trim(); + if (!Strings.isNullOrEmpty(str)) { + valueList.add(str); + } + } + String[] result = new String[valueList.size()]; + return valueList.toArray(result); + } + + private void initDb(GCPConfig config) { + String dbUrl = ""; + String driver = ""; + if (config.getDbType() == null) { + throw new IllegalArgumentException("db type cannot be null!"); + } else if (config.getDbType() == DbType.MYSQL) { + // mysql + dbUrl = "jdbc:mysql://" + config.getHostname() + ":" + config.getPort() + "/" + config.getSchema(); + driver = "com.mysql.cj.jdbc.Driver"; + } else if (config.getDbType() == DbType.ORACLE) { + dbUrl = "jdbc:oracle:thin:@" + config.getHostname() + ":" + config.getPort() + ":" + config.getSchema(); + driver = "oracle.jdbc.OracleDriver"; + } else if (config.getDbType() == DbType.SQL_SERVER) { + dbUrl = "jdbc:sqlserver://" + config.getHostname() + ":" + config.getPort() + ";DatabaseName=" + config.getSchema() + ";trustServerCertificate=true"; + driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; + } else { + throw new IllegalArgumentException("unsupported db type [" + config.getDbType() + "]!"); + } + config.setDbUrl(dbUrl); + config.setDriver(driver); + } +} diff --git a/src/main/java/com/baomidou/GenerateMojo.java b/src/main/java/com/baomidou/GenerateMojo.java deleted file mode 100644 index a1982f46b110eb36caa2711bfa8868bf85ce42d0..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/GenerateMojo.java +++ /dev/null @@ -1,265 +0,0 @@ -package com.baomidou; - -import com.baomidou.config.ConstVal; -import com.baomidou.config.TemplateConfig; -import com.baomidou.config.builder.ConfigBuilder; -import com.baomidou.config.po.TableField; -import com.baomidou.config.po.TableInfo; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; -import org.apache.velocity.app.VelocityEngine; - -import java.io.*; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.stream.Collectors; - -/** - * 生成文件 - * - * @author YangHu, tangguo - * @since 2016/8/30 - */ -@Mojo(name = "code", threadSafe = true) -public class GenerateMojo extends AbstractGenerateMojo { - - /** - * velocity引擎 - */ - private VelocityEngine engine; - - /** - * 输出文件 - */ - private Map outputFiles; - - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - log.info("==========================准备生成文件...=========================="); - // 初始化配置 - initConfig(); - // 初始化输出文件路径模板 - initOutputFiles(); - // 创建输出文件路径 - mkdirs(config.getPathInfo()); - // 获取上下文 - Map ctxData = analyzeData(config); - // 循环生成文件 - for (Map.Entry ctx : ctxData.entrySet()) { - batchOutput(ctx.getKey(), ctx.getValue()); - } - // 打开输出目录 - if (isOpen()) { - try { - String osName = System.getProperty("os.name"); - if (osName != null) { - if (osName.contains("Mac")) { - Runtime.getRuntime().exec("open " + getOutputDir()); - } else if (osName.contains("Windows")) { - Runtime.getRuntime().exec("cmd /c start " + getOutputDir()); - } else { - log.info("文件输出目录:" + getOutputDir()); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - } - log.info("==========================文件生成完成!!!=========================="); - } - - /** - * 分析数据 - * - * @param config - * 总配置信息 - * @return 解析数据结果集 - */ - private Map analyzeData(ConfigBuilder config) { - List tableList = config.getTableInfoList(); - Map packageInfo = config.getPackageInfo(); - Map ctxData = new HashMap<>(); - String superEntityClass = getSuperClassName(config.getSuperEntityClass()); - String superMapperClass = getSuperClassName(config.getSuperMapperClass()); - String superServiceClass = getSuperClassName(config.getSuperServiceClass()); - String superServiceImplClass = getSuperClassName(config.getSuperServiceImplClass()); - String superControllerClass = getSuperClassName(config.getSuperControllerClass()); - String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); - - for (TableInfo tableInfo : tableList) { - VelocityContext ctx = new VelocityContext(); - List tableFields = tableInfo.getFields().stream() - .filter(tableField -> "BigDecimal".equalsIgnoreCase(tableField.getPropertyType())) - .collect(Collectors.toList()); - if (CollectionUtils.isNotEmpty(tableFields)) { - ctx.put("havBigDecimal", true); - } else { - ctx.put("havBigDecimal", false); - } - - ctx.put("package", packageInfo); - ctx.put("table", tableInfo); - ctx.put("entity", tableInfo.getEntityName()); - ctx.put("addTabeName", !tableInfo.getEntityName().equalsIgnoreCase(tableInfo.getName())); - ctx.put("idGenType", config.getIdType()); - ctx.put("superEntityClassPackage", config.getSuperEntityClass()); - ctx.put("superEntityClass", superEntityClass); - ctx.put("superMapperClassPackage", config.getSuperMapperClass()); - ctx.put("superMapperClass", superMapperClass); - ctx.put("superServiceClassPackage", config.getSuperServiceClass()); - ctx.put("superServiceClass", superServiceClass); - ctx.put("superServiceImplClassPackage", config.getSuperServiceImplClass()); - ctx.put("superServiceImplClass", superServiceImplClass); - ctx.put("superControllerClassPackage", config.getSuperControllerClass()); - ctx.put("superControllerClass", superControllerClass); - ctx.put("enableCache", isEnableCache()); - ctx.put("author", getAuthor()); - ctx.put("activeRecord", isActiveRecord()); - ctx.put("enableSwagger", isEnableSwagger()); - ctx.put("date", date); - ctxData.put(tableInfo.getEntityName(), ctx); - } - return ctxData; - } - - /** - * 获取类名 - * - * @param classPath - * @return - */ - private String getSuperClassName(String classPath) { - if (StringUtils.isBlank(classPath)) { - return null; - } - return classPath.substring(classPath.lastIndexOf(".") + 1); - } - - /** - * 处理输出目录 - * - * @param pathInfo - * 路径信息 - */ - private void mkdirs(Map pathInfo) { - for (Map.Entry entry : pathInfo.entrySet()) { - File dir = new File(entry.getValue()); - if (!dir.exists()) { - boolean result = dir.mkdirs(); - if (result) { - log.info("创建目录: [" + entry.getValue() + "]"); - } - } - } - } - - /** - * 初始化输出目录 - */ - private void initOutputFiles() { - outputFiles = new HashMap(); - Map pathInfo = config.getPathInfo(); - outputFiles.put(ConstVal.ENTITY, pathInfo.get(ConstVal.ENTITY_PATH) + ConstVal.ENTITY_NAME); - outputFiles.put(ConstVal.MAPPER, pathInfo.get(ConstVal.MAPPER_PATH) + ConstVal.MAPPER_NAME); - outputFiles.put(ConstVal.XML, pathInfo.get(ConstVal.XML_PATH) + ConstVal.XML_NAME); - outputFiles.put(ConstVal.SERIVCE, pathInfo.get(ConstVal.SERIVCE_PATH) + ConstVal.SERVICE_NAME); - outputFiles.put(ConstVal.SERVICEIMPL, pathInfo.get(ConstVal.SERVICEIMPL_PATH) + ConstVal.SERVICEIMPL_NAME); - outputFiles.put(ConstVal.CONTROLLER, pathInfo.get(ConstVal.CONTROLLER_PATH) + ConstVal.CONTROLLER_NAME); - } - - /** - * 合成上下文与模板 - * - * @param context - * vm上下文 - */ - private void batchOutput(String entityName, VelocityContext context) { - try { - String entityFile = String.format(outputFiles.get(ConstVal.ENTITY), entityName); - String mapperFile = String.format(outputFiles.get(ConstVal.MAPPER), entityName); - String xmlFile = String.format(outputFiles.get(ConstVal.XML), entityName); - String serviceFile = String.format(outputFiles.get(ConstVal.SERIVCE), entityName); - String implFile = String.format(outputFiles.get(ConstVal.SERVICEIMPL), entityName); - String controllerFile = String.format(outputFiles.get(ConstVal.CONTROLLER), entityName); - - TemplateConfig template = config.getTemplate(); - - // 根据override标识来判断是否需要创建文件 - if (isCreate(entityFile)) { - vmToFile(context, template.getEntity(), entityFile); - } - if (isCreate(mapperFile)) { - vmToFile(context, template.getMapper(), mapperFile); - } - if (isCreate(xmlFile)) { - vmToFile(context, template.getXml(), xmlFile); - } - if (isCreate(serviceFile)) { - vmToFile(context, template.getService(), serviceFile); - } - if (isCreate(implFile)) { - vmToFile(context, template.getServiceImpl(), implFile); - } - if (isCreate(controllerFile)) { - vmToFile(context, template.getController(), controllerFile); - } - } catch (IOException e) { - log.error("无法创建文件,请检查配置信息!"); - e.printStackTrace(); - } - } - - /** - * 将模板转化成为文件 - * - * @param context - * 内容对象 - * @param templatePath - * 模板文件 - * @param outputFile - * 文件生成的目录 - */ - private void vmToFile(VelocityContext context, String templatePath, String outputFile) throws IOException { - VelocityEngine velocity = getVelocityEngine(); - Template template = velocity.getTemplate(templatePath, ConstVal.UTF8); - FileOutputStream fos = new FileOutputStream(outputFile); - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, ConstVal.UTF8)); - template.merge(context, writer); - writer.close(); - log.info("模板:" + templatePath + "; 文件:" + outputFile); - } - - /** - * 设置模版引擎,主要指向获取模版路径 - */ - private VelocityEngine getVelocityEngine() { - if (engine == null) { - Properties p = new Properties(); - p.setProperty(ConstVal.VM_LOADPATH_KEY, ConstVal.VM_LOADPATH_VALUE); - p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, ""); - p.setProperty(Velocity.ENCODING_DEFAULT, ConstVal.UTF8); - p.setProperty(Velocity.INPUT_ENCODING, ConstVal.UTF8); - p.setProperty(Velocity.OUTPUT_ENCODING, ConstVal.UTF8); - p.setProperty("file.resource.loader.unicode", "true"); - engine = new VelocityEngine(p); - } - return engine; - } - - /** - * 检测文件是否存在 - * - * @return 是否 - */ - private boolean isCreate(String filePath) { - File file = new File(filePath); - return !file.exists() || isFileOverride(); - } - -} diff --git a/src/main/java/com/baomidou/config/ConstVal.java b/src/main/java/com/baomidou/config/ConstVal.java deleted file mode 100644 index 8a29f6b078bb05142bfba49a82758d0d9b2bccb2..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/ConstVal.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.baomidou.config; - -import java.io.File; -import java.nio.charset.Charset; - -/** - * 定义常量 - * - * @author YangHu, tangguo - * @since 2016/8/31 - */ -public class ConstVal { - - public static final String MODULENAME = "ModuleName"; - - public static final String ENTITY = "Entity"; - public static final String SERIVCE = "Service"; - public static final String SERVICEIMPL = "ServiceImpl"; - public static final String MAPPER = "Mapper"; - public static final String XML = "Xml"; - public static final String CONTROLLER = "Controller"; - - public static final String ENTITY_PATH = "entity_path"; - public static final String SERIVCE_PATH = "serivce_path"; - public static final String SERVICEIMPL_PATH = "serviceimpl_path"; - public static final String MAPPER_PATH = "mapper_path"; - public static final String XML_PATH = "xml_path"; - public static final String CONTROLLER_PATH = "controller_path"; - - public static final String JAVA_TMPDIR = "java.io.tmpdir"; - public static final String UTF8 = Charset.forName("UTF-8").name(); - public static final String UNDERLINE = "_"; - - public static final String JAVA_SUFFIX = ".java"; - public static final String XML_SUFFIX = ".xml"; - - public static final String TEMPLATE_ENTITY = "/template/entity.java.vm"; - public static final String TEMPLATE_MAPPER = "/template/mapper.java.vm"; - public static final String TEMPLATE_XML = "/template/mapper.xml.vm"; - public static final String TEMPLATE_SERVICE = "/template/service.java.vm"; - public static final String TEMPLATE_SERVICEIMPL = "/template/serviceImpl.java.vm"; - public static final String TEMPLATE_CONTROLLER = "/template/controller.java.vm"; - - public static final String ENTITY_NAME = File.separator + "%s" + JAVA_SUFFIX; - public static final String MAPPER_NAME = File.separator + "%s" + MAPPER + JAVA_SUFFIX; - public static final String XML_NAME = File.separator + "%s" + MAPPER + XML_SUFFIX; - public static final String SERVICE_NAME = File.separator + "I%s" + SERIVCE + JAVA_SUFFIX; - public static final String SERVICEIMPL_NAME = File.separator + "%s" + SERVICEIMPL + JAVA_SUFFIX; - public static final String CONTROLLER_NAME = File.separator + "%s" + CONTROLLER + JAVA_SUFFIX; - - // 配置使用classloader加载资源 - public static final String VM_LOADPATH_KEY = "file.resource.loader.class"; - public static final String VM_LOADPATH_VALUE = "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"; - - public static final String SUPERD_MAPPER_CLASS = "com.baomidou.mybatisplus.mapper.BaseMapper"; - public static final String SUPERD_SERVICE_CLASS = "com.baomidou.framework.service.IService"; - public static final String SUPERD_SERVICEIMPL_CLASS = "com.baomidou.framework.service.impl.ServiceImpl"; - -} diff --git a/src/main/java/com/baomidou/config/DataSourceConfig.java b/src/main/java/com/baomidou/config/DataSourceConfig.java deleted file mode 100644 index 15ee29893922f840f0b04d22c91e3a397030dec3..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/DataSourceConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.baomidou.config; - -import com.baomidou.config.rules.DbType; -import org.apache.maven.plugins.annotations.Parameter; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -/** - * 数据库配置 - * - * @author YangHu - * @since 2016/8/30 - */ -public class DataSourceConfig { - - /** - * 数据库类型 - */ - @Parameter - private DbType dbType; - /** - * 驱动连接的URL - */ - @Parameter(required = true) - private String url; - /** - * 驱动名称 - */ - @Parameter(required = true) - private String driverName; - /** - * 数据库连接用户名 - */ - @Parameter(required = true) - private String username; - /** - * 数据库连接密码 - */ - @Parameter(required = true) - private String password; - - /** - * 判断数据库类型 - * - * @return 类型枚举值 - */ - public DbType getDbType() { - if (null == dbType) { - if (driverName.contains("mysql")) { - dbType = DbType.MYSQL; - } else if (driverName.contains("oracle")) { - dbType = DbType.ORACLE; - } - } - return dbType; - } - - /** - * 创建数据库连接对象 - * - * @return Connection - */ - public Connection getConn() { - Connection conn = null; - try { - Class.forName(driverName); - conn = DriverManager.getConnection(url, username, password); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (SQLException e) { - e.printStackTrace(); - } - return conn; - } - -} diff --git a/src/main/java/com/baomidou/config/GCPDatasourceConfig.java b/src/main/java/com/baomidou/config/GCPDatasourceConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..5bfa0f76e21ffa1fc599c7b787233989c1950ecc --- /dev/null +++ b/src/main/java/com/baomidou/config/GCPDatasourceConfig.java @@ -0,0 +1,27 @@ +package com.baomidou.config; + +import com.baomidou.mybatisplus.annotation.DbType; +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +@Data +public class GCPDatasourceConfig { + // 数据库类型 + @Parameter(required = true) + private DbType dbType; + // 数据库连接hostname或ip + @Parameter(required = true) + private String hostname; + // 数据库连接端口号 + @Parameter(required = true) + private Integer port; + // 数据库连接数据库 + @Parameter(required = true) + private String schema; + // 数据库名称 + @Parameter(required = true) + private String username; + // 数据库密码 + @Parameter(required = true) + private String password; +} diff --git a/src/main/java/com/baomidou/config/GCPGlobalConfig.java b/src/main/java/com/baomidou/config/GCPGlobalConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..52451c983ca1dd5ca94d530378fc9861378a7da3 --- /dev/null +++ b/src/main/java/com/baomidou/config/GCPGlobalConfig.java @@ -0,0 +1,29 @@ +package com.baomidou.config; + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +@Data +public class GCPGlobalConfig { + // 包名 + @Parameter(required = true) + private String rootPackage; + // 作者 + @Parameter + private String author; + // 逻辑删除字段 + @Parameter + private String fieldLogicDelete; + // 乐观锁字段 + @Parameter + private String fieldVersion; + // 模版引擎 + @Parameter + private String templateEngine; + // 实体父类的全类名 + @Parameter + private String superClassName; + // 实体父类的全类名 + @Parameter + private String superServiceImplClass; +} diff --git a/src/main/java/com/baomidou/config/GCPTableConfig.java b/src/main/java/com/baomidou/config/GCPTableConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..2db051bd4566a7665f420da3516689e0d25ec909 --- /dev/null +++ b/src/main/java/com/baomidou/config/GCPTableConfig.java @@ -0,0 +1,30 @@ +package com.baomidou.config; + +import lombok.Data; +import org.apache.maven.plugins.annotations.Parameter; + +@Data +public class GCPTableConfig { + // includeTables和excludeTables只能二选其一 + // 包含的表列表 + @Parameter + private String includeTables; + // 排除的表列表 + @Parameter + private String excludeTables; + // 表前缀 + @Parameter + private String tablePrefixes; + // 表后缀 + @Parameter + private String tableSuffixes; + // 字段前缀 + @Parameter + private String fieldPrefixes; + // 字段后缀 + @Parameter + private String fieldSuffixes; + // 忽略的字段 + @Parameter + private String ignoreColumns; +} diff --git a/src/main/java/com/baomidou/config/PackageConfig.java b/src/main/java/com/baomidou/config/PackageConfig.java deleted file mode 100644 index 5f3cc353225ae9236fa5d1ee65529a57f4305731..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/PackageConfig.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.baomidou.config; - -import org.apache.commons.lang.StringUtils; -import org.apache.maven.plugins.annotations.Parameter; - -/** - * 跟包相关的配置项 - * - * @author YangHu, tangguo - * @since 2016/8/30 - */ -public class PackageConfig { - - /** - * 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名 - */ - @Parameter(defaultValue = "com.baomidou") - private String parent; - - /** - * 父包模块名。 - */ - private String moduleName; - - /** - * Entity包名 - */ - @Parameter(defaultValue = "entity") - private String entity; - - /** - * Service包名 - */ - @Parameter(defaultValue = "service") - private String service; - - /** - * Service Impl包名 - */ - @Parameter(defaultValue = "service.impl") - private String serviceImpl; - /** - * Mapper包名 - */ - @Parameter(defaultValue = "mapper") - private String mapper; - - /** - * Mapper XML包名 - */ - @Parameter(defaultValue = "mapper.xml") - private String xml; - - /** - * Controller包名 - */ - @Parameter(defaultValue = "web") - private String controller; - - public String getParent() { - if(moduleName != null && !"".equals(moduleName.trim())) { - return parent + "." + moduleName; - } - return parent; - } - - public String getModuleName() { - return moduleName; - } - - public String getEntity() { - return entity; - } - - public String getService() { - return service; - } - - public String getServiceImpl() { - return serviceImpl; - } - - public String getMapper() { - return mapper; - } - - public String getXml() { - return xml; - } - - public String getController() { - if(StringUtils.isBlank(controller)) { - return "web"; - } - return controller; - } -} diff --git a/src/main/java/com/baomidou/config/StrategyConfig.java b/src/main/java/com/baomidou/config/StrategyConfig.java deleted file mode 100644 index dfc1b6bb4095769e9cd3326861cfc0bc0172c9b7..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/StrategyConfig.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.baomidou.config; - -import org.apache.maven.plugins.annotations.Parameter; - -import com.baomidou.config.rules.IdStrategy; -import com.baomidou.config.rules.NamingStrategy; - -/** - * 策略配置项 - * - * @author YangHu, tangguo, hubin - * @since 2016/8/30 - */ -public class StrategyConfig { - - /** - * 数据库表映射到实体的命名策略 - */ - @Parameter(defaultValue = "nochange") - private NamingStrategy naming; - - @Parameter(defaultValue = "underline_to_camel") - private NamingStrategy fieldNaming; - - /** - * 表前缀 - */ - @Parameter - private String tablePrefix; - - /** - * Entity 中的ID生成类型 - */ - @Parameter(defaultValue = "ID_WORKER") - private IdStrategy idGenType; - - /** - * 自定义继承的Entity类全称,带包名 - */ - @Parameter - private String superEntityClass; - - /** - * 自定义继承的Mapper类全称,带包名 - */ - @Parameter(defaultValue = ConstVal.SUPERD_MAPPER_CLASS) - private String superMapperClass; - - /** - * 自定义继承的Service类全称,带包名 - */ - @Parameter(defaultValue = ConstVal.SUPERD_SERVICE_CLASS) - private String superServiceClass; - - /** - * 自定义继承的ServiceImpl类全称,带包名 - */ - @Parameter(defaultValue = ConstVal.SUPERD_SERVICEIMPL_CLASS) - private String superServiceImplClass; - - /** - * 自定义继承的Controller类全称,带包名 - */ - @Parameter - private String superControllerClass; - - /* - * 需要包含的表名(与exclude二选一配置) - */ - @Parameter - private String[] include = null; - - /** - * 需要排除的表名 - */ - @Parameter - private String[] exclude = null; - - public NamingStrategy getNaming() { - return naming; - } - - public NamingStrategy getFieldNaming() { - if (fieldNaming == null) { - return naming; - } - return fieldNaming; - } - - public String getTablePrefix() { - return tablePrefix; - } - - public IdStrategy getIdGenType() { - return idGenType; - } - - public String[] getInclude() { - return include; - } - - public String[] getExclude() { - return exclude; - } - - public String getSuperServiceClass() { - return superServiceClass; - } - - public String getSuperEntityClass() { - return superEntityClass; - } - - public void setSuperEntityClass(String superEntityClass) { - this.superEntityClass = superEntityClass; - } - - public String getSuperMapperClass() { - return superMapperClass; - } - - public String getSuperServiceImplClass() { - return superServiceImplClass; - } - - public String getSuperControllerClass() { - return superControllerClass; - } - -} diff --git a/src/main/java/com/baomidou/config/TemplateConfig.java b/src/main/java/com/baomidou/config/TemplateConfig.java deleted file mode 100644 index f6a7dac86cbacdf5f281a0df41199e35bd773258..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/TemplateConfig.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.baomidou.config; - -import org.apache.maven.plugins.annotations.Parameter; - -/** - * - * @ClassName: TemplateConfig - * @Description: 模板路径配置项 - * @author tzg - * @date 2016年11月10日 下午4:45:12 - * - */ -public class TemplateConfig { - - @Parameter(defaultValue = ConstVal.TEMPLATE_ENTITY) - private String entity; - - @Parameter(defaultValue = ConstVal.TEMPLATE_SERVICE) - private String service; - - @Parameter(defaultValue = ConstVal.TEMPLATE_SERVICEIMPL) - private String serviceImpl; - - @Parameter(defaultValue = ConstVal.TEMPLATE_MAPPER) - private String mapper; - - @Parameter(defaultValue = ConstVal.TEMPLATE_XML) - private String xml; - - @Parameter(defaultValue = ConstVal.TEMPLATE_CONTROLLER) - private String controller; - - - public String getEntity() { - if(entity == null) return ConstVal.TEMPLATE_ENTITY; - return entity; - } - - public String getService() { - if(service == null) return ConstVal.TEMPLATE_SERVICE; - return service; - } - - public String getServiceImpl() { - if(serviceImpl == null) return ConstVal.TEMPLATE_SERVICEIMPL; - return serviceImpl; - } - - public String getMapper() { - if(mapper == null) return ConstVal.TEMPLATE_MAPPER; - return mapper; - } - - public String getXml() { - if(xml == null) return ConstVal.TEMPLATE_XML; - return xml; - } - - public String getController() { - if(controller == null) return ConstVal.TEMPLATE_CONTROLLER; - return controller; - } - - -} diff --git a/src/main/java/com/baomidou/config/builder/ConfigBuilder.java b/src/main/java/com/baomidou/config/builder/ConfigBuilder.java deleted file mode 100644 index ba18efe69a8dc648709bdf504d9a18dcf9856b5b..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/builder/ConfigBuilder.java +++ /dev/null @@ -1,546 +0,0 @@ -package com.baomidou.config.builder; - -import com.baomidou.config.*; -import com.baomidou.config.po.TableField; -import com.baomidou.config.po.TableInfo; -import com.baomidou.config.rules.DbType; -import com.baomidou.config.rules.IdStrategy; -import com.baomidou.config.rules.NamingStrategy; -import com.baomidou.config.rules.QuerySQL; -import org.apache.commons.lang.StringUtils; - -import java.io.File; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.*; - -/** - * 配置汇总 传递给文件生成工具 - * - * @author YangHu, tangguo, hubin - * @since 2016/8/30 - */ -public class ConfigBuilder { - - /** - * SQL连接 - */ - private Connection connection; - /** - * SQL语句类型 - */ - private QuerySQL querySQL; - private String superEntityClass; - private String superMapperClass; - /** - * service超类定义 - */ - private String superServiceClass; - private String superServiceImplClass; - private String superControllerClass; - /** - * ID的字符串类型 - */ - private String idType; - /** - * 数据库表信息 - */ - private List tableInfoList; - - /** - * 包配置详情 - */ - private Map packageInfo; - /** - * 路径配置信息 - */ - private Map pathInfo; - - /** - * 模板路径配置信息 - */ - private TemplateConfig template; - - /** - * 在构造器中处理配置 - * - * @param outputDir - * 输出目录 - * @param packageConfig - * 包配置 - * @param dataSourceConfig - * 数据源配置 - * @param strategyConfig - * 表配置 - */ - public ConfigBuilder(PackageConfig packageConfig, DataSourceConfig dataSourceConfig, StrategyConfig strategyConfig, - TemplateConfig template, String outputDir) { - handlerPackage(outputDir, packageConfig); - handlerDataSource(dataSourceConfig); - handlerStrategy(strategyConfig); - this.template = template; - } - - // ************************ 曝露方法 BEGIN***************************** - - /** - * 所有包配置信息 - * - * @return 包配置 - */ - public Map getPackageInfo() { - return packageInfo; - } - - /** - * 所有路径配置 - * - * @return 路径配置 - */ - public Map getPathInfo() { - return pathInfo; - } - - public String getSuperEntityClass() { - return superEntityClass; - } - - public String getSuperMapperClass() { - return superMapperClass; - } - - /** - * 获取超类定义 - * - * @return 完整超类名称 - */ - public String getSuperServiceClass() { - return superServiceClass; - } - - public String getSuperServiceImplClass() { - return superServiceImplClass; - } - - public String getSuperControllerClass() { - return superControllerClass; - } - - /** - * 获取ID类型 - * - * @return id生成方式 - */ - public String getIdType() { - return idType; - } - - /** - * 表信息 - * - * @return 所有表信息 - */ - public List getTableInfoList() { - return tableInfoList; - } - - /** - * 模板路径配置信息 - * - * @return 所以模板路径配置信息 - */ - public TemplateConfig getTemplate() { - return template == null ? new TemplateConfig() : template; - } - - // ****************************** 曝露方法 END********************************** - - /** - * 处理包配置 - * - * @param config - * PackageConfig - */ - private void handlerPackage(String outputDir, PackageConfig config) { - packageInfo = new HashMap(); - packageInfo.put(ConstVal.MODULENAME, config.getModuleName()); - packageInfo.put(ConstVal.ENTITY, joinPackage(config.getParent(), config.getEntity())); - packageInfo.put(ConstVal.MAPPER, joinPackage(config.getParent(), config.getMapper())); - packageInfo.put(ConstVal.XML, joinPackage("", config.getXml())); - packageInfo.put(ConstVal.SERIVCE, joinPackage(config.getParent(), config.getService())); - packageInfo.put(ConstVal.SERVICEIMPL, joinPackage(config.getParent(), config.getServiceImpl())); - packageInfo.put(ConstVal.CONTROLLER, joinPackage(config.getParent(), config.getController())); - - pathInfo = new HashMap(); - pathInfo.put(ConstVal.ENTITY_PATH, joinPath(outputDir, packageInfo.get(ConstVal.ENTITY))); - pathInfo.put(ConstVal.MAPPER_PATH, joinPath(outputDir, packageInfo.get(ConstVal.MAPPER))); - pathInfo.put(ConstVal.XML_PATH, packageInfo.get(ConstVal.XML)); - pathInfo.put(ConstVal.SERIVCE_PATH, joinPath(outputDir, packageInfo.get(ConstVal.SERIVCE))); - pathInfo.put(ConstVal.SERVICEIMPL_PATH, joinPath(outputDir, packageInfo.get(ConstVal.SERVICEIMPL))); - pathInfo.put(ConstVal.CONTROLLER_PATH, joinPath(outputDir, packageInfo.get(ConstVal.CONTROLLER))); - } - - /** - * 处理数据源配置 - * - * @param config - * DataSourceConfig - */ - private void handlerDataSource(DataSourceConfig config) { - connection = config.getConn(); - querySQL = getQuerySQL(config.getDbType()); - } - - /** - * 处理数据库表 加载数据库表、列、注释相关数据集 - * - * @param config - * StrategyConfig - */ - private void handlerStrategy(StrategyConfig config) { - processTypes(config); - tableInfoList = getTablesInfo(config); - } - - /** - * 处理superClassName,IdClassType,IdStrategy配置 - * - * @param config - * 策略配置 - */ - private void processTypes(StrategyConfig config) { - if (StringUtils.isBlank(config.getSuperServiceClass())) { - superServiceClass = ConstVal.SUPERD_SERVICE_CLASS; - } else { - superServiceClass = config.getSuperServiceClass(); - } - if (StringUtils.isBlank(config.getSuperServiceImplClass())) { - superServiceImplClass = ConstVal.SUPERD_SERVICEIMPL_CLASS; - } else { - superServiceImplClass = config.getSuperServiceImplClass(); - } - if (StringUtils.isBlank(config.getSuperMapperClass())) { - superMapperClass = ConstVal.SUPERD_MAPPER_CLASS; - } else { - superMapperClass = config.getSuperMapperClass(); - } - superEntityClass = config.getSuperEntityClass(); - superControllerClass = config.getSuperControllerClass(); - - // ID 策略判断 - if (config.getIdGenType() == IdStrategy.auto) { - idType = IdStrategy.auto.getValue(); - } else if (config.getIdGenType() == IdStrategy.input) { - idType = IdStrategy.input.getValue(); - } else if (config.getIdGenType() == IdStrategy.none) { - idType = IdStrategy.none.getValue(); - } else if (config.getIdGenType() == IdStrategy.assign_id) { - idType = IdStrategy.assign_id.getValue(); - }else if (config.getIdGenType() == IdStrategy.assign_uuid) { - idType = IdStrategy.assign_uuid.getValue(); - } else { - idType = IdStrategy.id_worker.getValue(); - } - } - - /** - * 处理表对应的类名称 - * - * @param tableList - * 表名称 - * @param strategy - * 命名策略 - * @param tablePrefix - * @return 补充完整信息后的表 - */ - private List processTable(List tableList, NamingStrategy strategy, String tablePrefix) { - for (TableInfo tableInfo : tableList) { - tableInfo.setEntityName(NamingStrategy.capitalFirst(processName(tableInfo.getName(), strategy, tablePrefix))); - tableInfo.setMapperName(tableInfo.getEntityName() + ConstVal.MAPPER); - tableInfo.setXmlName(tableInfo.getMapperName()); - tableInfo.setServiceName("I" + tableInfo.getEntityName() + ConstVal.SERIVCE); - tableInfo.setServiceImplName(tableInfo.getEntityName() + ConstVal.SERVICEIMPL); - tableInfo.setControllerName(tableInfo.getEntityName() + ConstVal.CONTROLLER); - } - return tableList; - } - - /** - * 获取所有的数据库表信息 - * - * @return 表信息 - */ - private List getTablesInfo(StrategyConfig config) { - boolean isInclude = (null != config.getInclude() && config.getInclude().length > 0); - boolean isExclude = (null != config.getExclude() && config.getExclude().length > 0); - List includes = Arrays.asList(Optional.ofNullable(config.getInclude()).orElse(new String[0])); - List excludes = Arrays.asList(Optional.ofNullable(config.getExclude()).orElse(new String[0])); - List tableList = new ArrayList(); - NamingStrategy strategy = config.getNaming(); - NamingStrategy fieldStrategy = config.getFieldNaming(); - String tablePrefix = config.getTablePrefix(); - PreparedStatement pstate = null; - try { - pstate = connection.prepareStatement(querySQL.getTableCommentsSql()); - ResultSet results = pstate.executeQuery(); - while (results.next()) { - String tableName = results.getString(querySQL.getTableName()); - if (tablePrefix != null && !tableName.toUpperCase().startsWith(tablePrefix.toUpperCase())) { - continue; - } - if (StringUtils.isNotBlank(tableName)) { - String tableComment = results.getString(querySQL.getTableComment()); - TableInfo tableInfo = new TableInfo(); - if (isInclude) { - if (includes.contains(tableName)) { - tableInfo.setName(tableName); - tableInfo.setComment(tableComment); - } - } else { - tableInfo.setName(tableName); - tableInfo.setComment(tableComment); - } - if (isExclude) { - if (excludes.contains(tableName)) { - continue; - } - } - if (StringUtils.isNotBlank(tableInfo.getName())) { - List fieldList = getListFields(tableInfo.getName(), fieldStrategy); - tableInfo.setFields(fieldList); - tableList.add(tableInfo); - } - } else { - System.err.println("当前数据库为空!!!"); - } - } - } catch (SQLException e) { - e.printStackTrace(); - } finally { - // 释放资源 - try { - if (pstate != null) { - pstate.close(); - } - if (connection != null) { - connection.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - return processTable(tableList, strategy, config.getTablePrefix()); - } - - /** - * 将字段信息与表信息关联 - * - * @param tableName - * 表名称 - * @param strategy - * 命名策略 - * @return 表信息 - */ - private List getListFields(String tableName, NamingStrategy strategy) throws SQLException { - boolean havedId = false; - - PreparedStatement pstate = connection.prepareStatement(String.format(querySQL.getTableFieldsSql(), tableName)); - ResultSet results = pstate.executeQuery(); - - List fieldList = new ArrayList(); - while (results.next()) { - TableField field = new TableField(); - String key = results.getString(querySQL.getFieldKey()); - // 避免多重主键设置,目前只取第一个找到ID,并放到list中的索引为0的位置 - boolean isId = StringUtils.isNotBlank(key) && key.toUpperCase().equals("PRI"); - // 处理ID - if (isId && !havedId) { - field.setKeyFlag(true); - havedId = true; - } else { - field.setKeyFlag(false); - } - // 处理其它信息 - field.setName(results.getString(querySQL.getFieldName())); - field.setType(results.getString(querySQL.getFieldType())); - field.setPropertyName(processName(field.getName(), strategy)); - field.setPropertyType(processFiledType(field.getType())); - field.setComment(results.getString(querySQL.getFieldComment())); - fieldList.add(field); - } - return fieldList; - } - - /** - * 连接路径字符串 - * - * @param parentDir - * 路径常量字符串 - * @param packageName - * 包名 - * @return 连接后的路径 - */ - private String joinPath(String parentDir, String packageName) { - if (StringUtils.isEmpty(parentDir)) { - parentDir = System.getProperty(ConstVal.JAVA_TMPDIR); - } - if (!StringUtils.endsWith(parentDir, File.separator)) { - parentDir += File.separator; - } - packageName = packageName.replaceAll("\\.", "\\" + File.separator); - return parentDir + packageName; - } - - /** - * 连接父子包名 - * - * @param parent - * 父包名 - * @param subPackage - * 子包名 - * @return 连接后的包名 - */ - private String joinPackage(String parent, String subPackage) { - if (StringUtils.isBlank(parent)) { - return subPackage; - } - return parent + "." + subPackage; - } - - /** - * 处理字段类型 - * - * @return 转换成JAVA包装类型 - */ - private String processFiledType(String type) { - if (QuerySQL.MYSQL == querySQL) { - return processMySqlType(type); - } else if (QuerySQL.ORACLE == querySQL) { - return processOracleType(type); - } - return null; - } - - /** - * 处理字段名称 - * - * @return 根据策略返回处理后的名称 - */ - private String processName(String name, NamingStrategy strategy) { - return processName(name, strategy, null); - } - - /** - * 处理字段名称 - * - * @param name - * @param strategy - * @param tablePrefix - * @return 根据策略返回处理后的名称 - */ - private String processName(String name, NamingStrategy strategy, String tablePrefix) { - String propertyName = ""; - switch (strategy) { - case remove_prefix_and_camel: - propertyName = NamingStrategy.removePrefixAndCamel(name, tablePrefix); - break; - case underline_to_camel: - propertyName = NamingStrategy.underlineToCamel(name); - break; - case remove_prefix: - propertyName = NamingStrategy.removePrefix(name, tablePrefix); - break; - case remove_underline: - propertyName = NamingStrategy.removeUnderline(name); - break; - case remove_underline_and_camel: - propertyName = NamingStrategy.removeUnderlineAndCamel(name); - break; - default: - propertyName = name; - } - return propertyName; - } - - /** - * MYSQL字段类型转换 - * - * @param type - * 字段类型 - * @return JAVA类型 - */ - private String processMySqlType(String type) { - String t = type.toLowerCase(); - if (t.contains("char") || t.contains("text")) { - return "String"; - } else if (t.contains("bigint")) { - return "Long"; - } else if (t.contains("int")) { - return "Integer"; - } else if (t.contains("date") || t.contains("time") || t.contains("year")) { - return "Date"; - } else if (t.contains("text")) { - return "String"; - } else if (t.contains("bit")) { - return "Boolean"; - } else if (t.contains("decimal")) { - return "BigDecimal"; - } else if (t.contains("blob")) { - return "byte[]"; - } else if (t.contains("float")) { - return "Float"; - } else if (t.contains("double")) { - return "Double"; - } else if (t.contains("json") || t.contains("enum")) { - return "String"; - } - return "String"; - } - - /** - * ORACLE字段类型转换 - * - * @param type - * 字段类型 - * @return JAVA类型 - */ - private String processOracleType(String type) { - String t = type.toUpperCase(); - if (t.contains("CHAR")) { - return "String"; - } else if (t.contains("DATE") || t.contains("TIMESTAMP")) { - return "Date"; - } else if (t.contains("NUMBER")) { - if (t.matches("NUMBER\\(+\\d{1}+\\)")) { - return "Integer"; - } else if (t.matches("NUMBER\\(+\\d{2}+\\)")) { - return "Long"; - } - return "Double"; - } else if (t.contains("FLOAT")) { - return "Float"; - } else if (t.contains("BLOB")) { - return "Object"; - } else if (t.contains("RAW")) { - return "byte[]"; - } - return "String"; - } - - /** - * 获取当前的SQL类型 - * - * @return DB类型 - */ - private QuerySQL getQuerySQL(DbType dbType) { - for (QuerySQL qs : QuerySQL.values()) { - if (qs.getDbType().equals(dbType.getValue())) { - return qs; - } - } - return QuerySQL.MYSQL; - } - -} diff --git a/src/main/java/com/baomidou/config/po/TableField.java b/src/main/java/com/baomidou/config/po/TableField.java deleted file mode 100644 index 2c85d34cae8c2bdc88feb38746a2cb5fb17fb67b..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/po/TableField.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.baomidou.config.po; - -/** - * Developer:YangHu - * Date:2016-9-3 - * Describe: 字段信息 - */ -public class TableField { - private boolean keyFlag; - private String name; - private String type; - private String propertyName; - private String propertyType; - private String comment; - - public boolean isKeyFlag() { - return keyFlag; - } - - public void setKeyFlag(boolean keyFlag) { - this.keyFlag = keyFlag; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getPropertyName() { - return propertyName; - } - - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } - - public String getPropertyType() { - return propertyType; - } - - public void setPropertyType(String propertyType) { - this.propertyType = propertyType; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - public boolean isConvert() { - return !name.equals(propertyName); - } - - public String getCapitalName() { - return propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); - } -} diff --git a/src/main/java/com/baomidou/config/po/TableInfo.java b/src/main/java/com/baomidou/config/po/TableInfo.java deleted file mode 100644 index 5cba13f2f325af023e18f20188b40ed6a54a064b..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/po/TableInfo.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.baomidou.config.po; - - -import org.apache.commons.lang.StringUtils; - -import java.util.List; - -/** - * 表信息,关联到当前字段信息 - * - * @author YangHu - * @since 2016/8/30 - */ -public class TableInfo { - - private String name; - private String comment; - - private String entityName; - private String mapperName; - private String xmlName; - private String serviceName; - private String serviceImplName; - private String controllerName; - - private List fields; - private String fieldNames; - private boolean hasDate; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - public String getEntityName() { - return entityName; - } - - public void setEntityName(String entityName) { - this.entityName = entityName; - } - - public String getMapperName() { - return mapperName; - } - - public void setMapperName(String mapperName) { - this.mapperName = mapperName; - } - - public String getXmlName() { - return xmlName; - } - - public void setXmlName(String xmlName) { - this.xmlName = xmlName; - } - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public String getServiceImplName() { - return serviceImplName; - } - - public void setServiceImplName(String serviceImplName) { - this.serviceImplName = serviceImplName; - } - - public String getControllerName() { - return controllerName; - } - - public void setControllerName(String controllerName) { - this.controllerName = controllerName; - } - - public List getFields() { - return fields; - } - - public void setFields(List fields) { - this.fields = fields; - } - - /** - * 转换filed实体为xmlmapper中的basecolumn字符串信息 - * - * @return - */ - public String getFieldNames() { - if (StringUtils.isBlank(fieldNames)) { - StringBuilder names = new StringBuilder(); - for (int i = 0; i < fields.size(); i++) { - TableField fd = fields.get(i); - if (i == fields.size() - 1) { - names.append(cov2col(fd)); - } else { - names.append(cov2col(fd)).append(", "); - } - } - fieldNames = names.toString(); - } - return fieldNames; - } - - /** - * 判断字段中是否包含日期类型 - * - * @return 是否 - */ - public boolean isHasDate() { - for (TableField fieldInfo : fields) { - if (fieldInfo.getPropertyType().equals("Date")) { - hasDate = true; - break; - } - } - return hasDate; - } - - /** - * mapper xml中的字字段添加as - * - * @param field 字段实体 - * @return 转换后的信息 - */ - private String cov2col(TableField field) { - if (null != field) { - return field.isConvert() ? field.getName() + " AS " + field.getPropertyName() : field.getName(); - } - return StringUtils.EMPTY; - } -} diff --git a/src/main/java/com/baomidou/config/rules/DbType.java b/src/main/java/com/baomidou/config/rules/DbType.java deleted file mode 100644 index dcccc70e62351c9c49dd6fac7896c784cba7d545..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/rules/DbType.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baomidou.config.rules; - -/** - * 数据库类型定义 - * - * @author YangHu - * @since 2016/8/30 - */ -public enum DbType { - - MYSQL("myslq"), ORACLE("oracle"); - - private String value; - - DbType(String value) { - this.value = value; - } - - public String getValue() { - return value; - } -} diff --git a/src/main/java/com/baomidou/config/rules/IdStrategy.java b/src/main/java/com/baomidou/config/rules/IdStrategy.java deleted file mode 100644 index 27d8e4c8e46a6cd95bed3a16a0d54554738dd6e8..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/rules/IdStrategy.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baomidou.config.rules; - -/** - * ID生成策略 - * - * @author YangHu - * @since 2016/8/30 - */ -public enum IdStrategy { - auto("AUTO"), none("NONE"), assign_id("ASSIGN_ID"), assign_uuid("ASSIGN_UUID"),id_worker("ID_WORKER"), uuid("UUID"), input("INPUT"); - - private String value; - - IdStrategy(String value) { - this.value = value; - } - - public String getValue() { - return value; - } -} diff --git a/src/main/java/com/baomidou/config/rules/NamingStrategy.java b/src/main/java/com/baomidou/config/rules/NamingStrategy.java deleted file mode 100644 index a9bae0c901fa9a139215c8e98fb2564d1a10649d..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/rules/NamingStrategy.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.baomidou.config.rules; - -import com.baomidou.config.ConstVal; -import org.apache.commons.lang.StringUtils; - -/** - * 从数据库表到文件的命名策略 - * - * @author YangHu, tangguo - * @since 2016/8/30 - */ -public enum NamingStrategy { - /** - * 不做任何改变,原样输出 - */ - nochange, - /** - * 下划线转驼峰命名 - */ - underline_to_camel, - /** - * 仅去掉前缀 - */ - remove_prefix, - /** - * 去掉前缀并且转驼峰 - */ - remove_prefix_and_camel, - /** - * 去掉第一个下划线之前内容,后面原样输出 - */ - remove_underline, - /** - * 去掉第一个下划线之前内容,后面转驼峰 - */ - remove_underline_and_camel; - - public static String underlineToCamel(String name) { - // 快速检查 - if (StringUtils.isBlank(name)) { - // 没必要转换 - return ""; - } - StringBuilder result = new StringBuilder(); - // 用下划线将原始字符串分割 - String camels[] = name.toLowerCase().split(ConstVal.UNDERLINE); - for (String camel : camels) { - // 跳过原始字符串中开头、结尾的下换线或双重下划线 - if (StringUtils.isBlank(camel)) { - continue; - } - // 处理真正的驼峰片段 - if (result.length() == 0) { - // 第一个驼峰片段,全部字母都小写 - result.append(camel); - } else { - // 其他的驼峰片段,首字母大写 - result.append(capitalFirst(camel)); - } - } - return result.toString(); - } - - /** - * 去掉第一个下划线之前内容,后面原样输出 - * - * @param name - * @return - */ - public static String removeUnderline(String name) { - if (StringUtils.isBlank(name)) { - return ""; - } - int idx = name.indexOf(ConstVal.UNDERLINE); - if (idx == -1) { - return name; - } - return name.substring(idx + 1); - } - - /** - * 去掉第一个下划线之前内容,后面转驼峰 - * - * @param name - * @return - */ - public static String removeUnderlineAndCamel(String name) { - return underlineToCamel(removeUnderline(name)); - } - - /** - * 去掉指定的前缀 - * @param name - * @param prefix - * @return - */ - public static String removePrefix(String name, String prefix) { - if (StringUtils.isBlank(name)) { - return ""; - } - int idx = -1; - if (prefix != null && !"".equals(prefix.trim())) { - idx = name.indexOf(ConstVal.UNDERLINE); - if (name.toLowerCase().matches("^" + prefix.toLowerCase() + ".*")) { // 判断是否有匹配的前缀,然后截取前缀 - idx = prefix.length() - 1; - } - } - if (idx == -1) { - return name; - } - return name.substring(idx + 1); - } - - /** - * 去掉下划线前缀且将后半部分转成驼峰格式 - * - * @param name - * @param tablePrefix - * @return - */ - public static String removePrefixAndCamel(String name, String tablePrefix) { - return underlineToCamel(removePrefix(name, tablePrefix)); - } - - /** - * 实体首字母大写 - * - * @param name 待转换的字符串 - * @return 转换后的字符串 - */ - public static String capitalFirst(String name) { - if (StringUtils.isNotBlank(name)) { - //return name.substring(0, 1).toUpperCase() + name.substring(1); - char[] array = name.toCharArray(); - array[0] -= 32; - return String.valueOf(array); - } - return ""; - } - -} diff --git a/src/main/java/com/baomidou/config/rules/QuerySQL.java b/src/main/java/com/baomidou/config/rules/QuerySQL.java deleted file mode 100644 index 83b7f5d3a17b2acbf3e513df51cc555ba27ba6d1..0000000000000000000000000000000000000000 --- a/src/main/java/com/baomidou/config/rules/QuerySQL.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.baomidou.config.rules; - -/** - *

- * 表数据查询 - *

- * - * @author hubin, tangguo - * @since 2016-04-25 - */ -public enum QuerySQL { - MYSQL("mysql", "show tables", "show table status", - "show full fields from %s", - "NAME", "COMMENT", "FIELD", "TYPE", "COMMENT", "KEY"), - - ORACLE("oracle", "SELECT * FROM USER_TABLES", "SELECT * FROM USER_TAB_COMMENTS", - "SELECT A.COLUMN_NAME, CASE WHEN A.DATA_TYPE='NUMBER' THEN " + - "(CASE WHEN A.DATA_PRECISION IS NULL THEN A.DATA_TYPE " + - "WHEN NVL(A.DATA_SCALE, 0) > 0 THEN A.DATA_TYPE||'('||A.DATA_PRECISION||','||A.DATA_SCALE||')' " + - "ELSE A.DATA_TYPE||'('||A.DATA_PRECISION||')' END) " + - "ELSE A.DATA_TYPE END DATA_TYPE, B.COMMENTS,DECODE(C.POSITION, '1', 'PRI') KEY " + - "FROM USER_TAB_COLUMNS A INNER JOIN USER_COL_COMMENTS B ON A.TABLE_NAME = B.TABLE_NAME" + - " AND A.COLUMN_NAME = B.COLUMN_NAME LEFT JOIN USER_CONSTRAINTS D " + - "ON D.TABLE_NAME = A.TABLE_NAME AND D.CONSTRAINT_TYPE = 'P' " + - "LEFT JOIN USER_CONS_COLUMNS C ON C.CONSTRAINT_NAME = D.CONSTRAINT_NAME " + - "AND C.COLUMN_NAME=A.COLUMN_NAME WHERE A.TABLE_NAME = '%s' ", - "TABLE_NAME", "COMMENTS", "COLUMN_NAME", "DATA_TYPE", "COMMENTS", "KEY"); - - private final String dbType; - private final String tablesSql; - private final String tableCommentsSql; - private final String tableFieldsSql; - private final String tableName; - private final String tableComment; - private final String fieldName; - private final String fieldType; - private final String fieldComment; - private final String fieldKey; - - - QuerySQL(final String dbType, final String tablesSql, final String tableCommentsSql, - final String tableFieldsSql, final String tableName, final String tableComment, final String fieldName, - final String fieldType, final String fieldComment, final String fieldKey) { - this.dbType = dbType; - this.tablesSql = tablesSql; - this.tableCommentsSql = tableCommentsSql; - this.tableFieldsSql = tableFieldsSql; - this.tableName = tableName; - this.tableComment = tableComment; - this.fieldName = fieldName; - this.fieldType = fieldType; - this.fieldComment = fieldComment; - this.fieldKey = fieldKey; - } - - public String getDbType() { - return dbType; - } - - public String getTablesSql() { - return tablesSql; - } - - public String getTableCommentsSql() { - return tableCommentsSql; - } - - public String getTableFieldsSql() { - return tableFieldsSql; - } - - public String getTableName() { - return tableName; - } - - public String getTableComment() { - return tableComment; - } - - public String getFieldName() { - return fieldName; - } - - public String getFieldType() { - return fieldType; - } - - public String getFieldComment() { - return fieldComment; - } - - public String getFieldKey() { - return fieldKey; - } - -} diff --git a/src/main/resources/template/controller.java.vm b/src/main/resources/template/controller.java.vm index e709a01cf5d57377817e314301cfddc343a019c0..da07d89a1fcdc279a70ceaf77afcf34ecea915cc 100644 --- a/src/main/resources/template/controller.java.vm +++ b/src/main/resources/template/controller.java.vm @@ -1,26 +1,46 @@ -package ${package.Controller}; - -#if(${enableSwagger}) - -import io.swagger.annotations.Api; -#end -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - *

- * ${table.comment} 前端控制器 - *

- * - * @author ${author} - * @since ${date} - */ -#if(${enableSwagger}) - -@Api(tags = "${table.comment}") -#end -@RestController -@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/${table.entityName.toLowerCase()}") -public class ${table.controllerName} { - -} +package ${package.Controller}; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import $!{package.Entity}.$!{entity}; +import $!{package.Service}.$!{table.serviceName}; +import io.swagger.annotations.Api; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + +/** + * 业务表$!{table.name}前端控制器 + * + * @author ${author} + */ +@Api(tags = "业务表$!{table.name}接口") +@RestController +@RequestMapping("/outward/${table.name}") +#if(${superControllerClass}) +public class ${table.controllerName} extends ${superControllerClass} { +#else +public class ${table.controllerName} { +#end + @Resource + private $!{table.serviceName} $!{table.entityPath}Service; + + @PostMapping("/save") + public ResponseEntity save(@RequestBody $!{entity} $!{table.entityPath}) { + return ResponseEntity.ok($!{table.entityPath}Service.save($!{table.entityPath})); + } + + @PostMapping("/update") + public ResponseEntity update(@RequestBody $!{entity} $!{table.entityPath}) { + return ResponseEntity.ok($!{table.entityPath}Service.updateById($!{table.entityPath})); + } + + @PostMapping("/selectByPage") + public ResponseEntity> selectByPage(@RequestParam(value = "current",defaultValue = "0") Integer current, + @RequestParam(value = "size",defaultValue = "20") Integer size, + @RequestBody(required = false) $!{entity} $!{table.entityPath}) { + return ResponseEntity.ok($!{table.entityPath}Service.page(new Page<>(current, size), new QueryWrapper<>($!{table.entityPath}))); + } +} diff --git a/src/main/resources/template/entity.java.vm b/src/main/resources/template/entity.java.vm deleted file mode 100644 index fed314df03aa08410e218a67cb1edafa28406873..0000000000000000000000000000000000000000 --- a/src/main/resources/template/entity.java.vm +++ /dev/null @@ -1,70 +0,0 @@ -package ${package.Entity}; - -#if(${activeRecord}) -import com.baomidou.mybatisplus.activerecord.Model; -#end -#if(${idGenType}!="ID_WORKER") -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableId; -#end -import com.baomidou.mybatisplus.annotation.TableField; -#if(${addTabeName}) -import com.baomidou.mybatisplus.annotation.TableName; -#end -#if(${enableSwagger}) -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -#end -import lombok.Data; -import lombok.experimental.Accessors; -import java.io.Serializable; -#if(${havBigDecimal}) -import java.math.BigDecimal; -#end -#if(${table.hasDate}) -import java.util.Date; -#end - -/** - *

- * ${table.comment} - *

- * - * @author ${author} - * @since ${date} - */ -@Data -@Accessors(chain = true) -#if(${enableSwagger}) - -@ApiModel("${table.comment}") -#end -#if(${addTabeName}) -@TableName("${table.name}") -#end -#if(${activeRecord}) -public class ${entity} extends Model<${entity}> { -#else -public class ${entity} implements Serializable{ -#end - - private static final long serialVersionUID=1L; - -#foreach($field in ${table.fields}) -#if(${field.comment.equals("")}) -#else - /** ${field.comment} */ -#end -#if(${field.keyFlag} && ${idGenType}!="ID_WORKER") - @TableId(type = IdType.${idGenType}) -#end -#if(${enableSwagger}) - @ApiModelProperty("${field.comment}") -#end -#if($field.convert && ${field.name.toLowerCase()} != ${field.propertyName.toLowerCase()}) - @TableField(value = "${field.name}") -#end - private ${field.propertyType} ${field.propertyName}; -#end - -} diff --git a/src/main/resources/template/mapper.java.vm b/src/main/resources/template/mapper.java.vm deleted file mode 100644 index feed2957d628f5feb6110a87bf914d470c827a53..0000000000000000000000000000000000000000 --- a/src/main/resources/template/mapper.java.vm +++ /dev/null @@ -1,16 +0,0 @@ -package ${package.Mapper}; - -import ${package.Entity}.${entity}; -import ${superMapperClassPackage}; - -/** - *

- * Mapper接口 - *

- * - * @author ${author} - * @since ${date} - */ -public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { - -} \ No newline at end of file diff --git a/src/main/resources/template/mapper.xml.vm b/src/main/resources/template/mapper.xml.vm deleted file mode 100644 index a907ddcbf589e7e65db9620f791dd19478d7c69c..0000000000000000000000000000000000000000 --- a/src/main/resources/template/mapper.xml.vm +++ /dev/null @@ -1,23 +0,0 @@ - - - -#if(${enableCache}) - - -#end - - -#foreach($field in ${table.fields}) -#if(${field.keyFlag}) - -#else - -#end -#end - - - - - ${table.fieldNames} - - diff --git a/src/main/resources/template/service.java.vm b/src/main/resources/template/service.java.vm deleted file mode 100644 index 343b90a58fba825dc61fde8adb0b8642078d44a3..0000000000000000000000000000000000000000 --- a/src/main/resources/template/service.java.vm +++ /dev/null @@ -1,16 +0,0 @@ -package ${package.Service}; - -import ${package.Entity}.${entity}; -import ${superServiceClassPackage}; - -/** - *

- * 服务类 - *

- * - * @author ${author} - * @since ${date} - */ -public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { - -} diff --git a/src/main/resources/template/serviceImpl.java.vm b/src/main/resources/template/serviceImpl.java.vm deleted file mode 100644 index 3a92c3cbb3a0fcd00f11c95986cb792ee7925327..0000000000000000000000000000000000000000 --- a/src/main/resources/template/serviceImpl.java.vm +++ /dev/null @@ -1,20 +0,0 @@ -package ${package.ServiceImpl}; - -import ${package.Entity}.${entity}; -import ${package.Mapper}.${table.mapperName}; -import ${package.Service}.${table.serviceName}; -import ${superServiceImplClassPackage}; -import org.springframework.stereotype.Service; - -/** - *

- * ${table.comment} 服务实现类 - *

- * - * @author ${author} - * @since ${date} - */ -@Service -public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { - -}