From bf869dc299e119e7ae322fbefc3b77d938932869 Mon Sep 17 00:00:00 2001 From: mengweijin <1002284406@qq.com> Date: Tue, 22 Dec 2020 22:52:40 +0800 Subject: [PATCH 1/7] refactor code. --- .../generator/{main => }/CodeGenerator.java | 51 ++++---- .../generator/{dto => }/DbInfo.java | 5 +- .../ConfigParameter.java => Parameters.java} | 22 ++-- .../generator/config/ConfigFactory.java | 111 ------------------ ...igImpl.java => CustomerFileOutConfig.java} | 15 ++- .../DefaultDataSourceConfig.java} | 110 ++++++----------- .../generator/config/DefaultGlobalConfig.java | 41 +++++++ .../config/DefaultInjectionConfig.java | 27 +++++ .../config/DefaultPackageConfig.java | 33 ++++++ .../config/DefaultStrategyConfig.java | 71 +++++++++++ .../config/DefaultTemplateConfig.java | 32 +++++ .../generator/config/InjectionConfigImpl.java | 105 ----------------- .../factory/TemplateEngineFactory.java | 34 ++++++ .../generator/mojo/AbstractGeneratorMojo.java | 29 ++--- .../generator/mojo/JpaGeneratorMojo.java | 17 ++- .../generator/mojo/MybatisGeneratorMojo.java | 13 +- .../mojo/MybatisPlusGeneratorMojo.java | 24 ++-- .../generator/reader/BootFileReader.java | 2 +- .../reader/BootFileReaderFactory.java | 3 +- .../reader/PropertiesBootFileReader.java | 2 +- .../generator/reader/YamlBootFileReader.java | 2 +- .../generator/util/FileOutConfigUtils.java | 38 +++--- 22 files changed, 382 insertions(+), 405 deletions(-) rename src/main/java/com/github/mengweijin/generator/{main => }/CodeGenerator.java (36%) rename src/main/java/com/github/mengweijin/generator/{dto => }/DbInfo.java (70%) rename src/main/java/com/github/mengweijin/generator/{dto/ConfigParameter.java => Parameters.java} (60%) delete mode 100644 src/main/java/com/github/mengweijin/generator/config/ConfigFactory.java rename src/main/java/com/github/mengweijin/generator/config/{FileOutConfigImpl.java => CustomerFileOutConfig.java} (81%) rename src/main/java/com/github/mengweijin/generator/{dto/DefaultConfigParameter.java => config/DefaultDataSourceConfig.java} (45%) create mode 100644 src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java create mode 100644 src/main/java/com/github/mengweijin/generator/config/DefaultInjectionConfig.java create mode 100644 src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java create mode 100644 src/main/java/com/github/mengweijin/generator/config/DefaultStrategyConfig.java create mode 100644 src/main/java/com/github/mengweijin/generator/config/DefaultTemplateConfig.java delete mode 100644 src/main/java/com/github/mengweijin/generator/config/InjectionConfigImpl.java create mode 100644 src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java diff --git a/src/main/java/com/github/mengweijin/generator/main/CodeGenerator.java b/src/main/java/com/github/mengweijin/generator/CodeGenerator.java similarity index 36% rename from src/main/java/com/github/mengweijin/generator/main/CodeGenerator.java rename to src/main/java/com/github/mengweijin/generator/CodeGenerator.java index 513e369..575ccce 100644 --- a/src/main/java/com/github/mengweijin/generator/main/CodeGenerator.java +++ b/src/main/java/com/github/mengweijin/generator/CodeGenerator.java @@ -1,55 +1,60 @@ -package com.github.mengweijin.generator.main; +package com.github.mengweijin.generator; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.FileOutConfig; -import com.github.mengweijin.generator.config.ConfigFactory; -import com.github.mengweijin.generator.config.InjectionConfigImpl; -import com.github.mengweijin.generator.dto.DefaultConfigParameter; +import com.github.mengweijin.generator.config.DefaultInjectionConfig; import com.github.mengweijin.generator.util.FileOutConfigUtils; - +import com.github.mengweijin.generator.config.DefaultDataSourceConfig; +import com.github.mengweijin.generator.config.DefaultGlobalConfig; +import com.github.mengweijin.generator.config.DefaultPackageConfig; +import com.github.mengweijin.generator.config.DefaultStrategyConfig; +import com.github.mengweijin.generator.config.DefaultTemplateConfig; +import com.github.mengweijin.generator.factory.TemplateEngineFactory; +import lombok.Data; +import org.apache.maven.model.Resource; +import java.io.File; import java.util.List; /** * @author mengweijin */ +@Data public class CodeGenerator { - /** - * 代码生成器 - */ - private final AutoGenerator autoGenerator = new AutoGenerator(); + private AutoGenerator autoGenerator; - private final DefaultConfigParameter parameter; + private Parameters parameters; - public CodeGenerator(DefaultConfigParameter parameter) { - this.parameter = parameter; - } + private List resourceList; + + private File baseDir; + + private File sourceDir; public void run() { + autoGenerator = new AutoGenerator(); // 全局配置 - autoGenerator.setGlobalConfig(ConfigFactory.getGlobalConfig(parameter)); + autoGenerator.setGlobalConfig(new DefaultGlobalConfig(this)); // 数据源配置 - autoGenerator.setDataSource(ConfigFactory.getDataSourceConfig(parameter)); + autoGenerator.setDataSource(new DefaultDataSourceConfig(this)); // 包配置 - autoGenerator.setPackageInfo(ConfigFactory.getPackageConfig(parameter)); + autoGenerator.setPackageInfo(new DefaultPackageConfig(this)); // Mybatis-plus自己的模板配置 - autoGenerator.setTemplate(ConfigFactory.getTemplateConfig(parameter)); + autoGenerator.setTemplate(new DefaultTemplateConfig(this)); // 自定义配置, 会被优先输出 - InjectionConfig injectionConfig = new InjectionConfigImpl(parameter, autoGenerator); - List fileOutConfigList = FileOutConfigUtils.loadTemplatesToGetFileOutConfig(parameter, autoGenerator); + InjectionConfig injectionConfig = new DefaultInjectionConfig(this); + List fileOutConfigList = FileOutConfigUtils.loadTemplatesToGetFileOutConfig(this); // TODO check file exits. - - injectionConfig.setFileOutConfigList(fileOutConfigList); autoGenerator.setCfg(injectionConfig); // 策略配置 - autoGenerator.setStrategy(ConfigFactory.getStrategyConfig(parameter)); + autoGenerator.setStrategy(new DefaultStrategyConfig(this)); // 模板引擎 - autoGenerator.setTemplateEngine(ConfigFactory.getTemplateEngine(parameter)); + autoGenerator.setTemplateEngine(TemplateEngineFactory.getTemplateEngine(this.parameters.getTemplateType())); autoGenerator.execute(); } diff --git a/src/main/java/com/github/mengweijin/generator/dto/DbInfo.java b/src/main/java/com/github/mengweijin/generator/DbInfo.java similarity index 70% rename from src/main/java/com/github/mengweijin/generator/dto/DbInfo.java rename to src/main/java/com/github/mengweijin/generator/DbInfo.java index f44bae7..48a3a0b 100644 --- a/src/main/java/com/github/mengweijin/generator/dto/DbInfo.java +++ b/src/main/java/com/github/mengweijin/generator/DbInfo.java @@ -1,7 +1,10 @@ -package com.github.mengweijin.generator.dto; +package com.github.mengweijin.generator; import lombok.Data; +/** + * @author mengweijin + */ @Data public class DbInfo { diff --git a/src/main/java/com/github/mengweijin/generator/dto/ConfigParameter.java b/src/main/java/com/github/mengweijin/generator/Parameters.java similarity index 60% rename from src/main/java/com/github/mengweijin/generator/dto/ConfigParameter.java rename to src/main/java/com/github/mengweijin/generator/Parameters.java index 1eaf91d..a539061 100644 --- a/src/main/java/com/github/mengweijin/generator/dto/ConfigParameter.java +++ b/src/main/java/com/github/mengweijin/generator/Parameters.java @@ -1,28 +1,26 @@ -package com.github.mengweijin.generator.dto; +package com.github.mengweijin.generator; import com.github.mengweijin.generator.enums.TemplateType; import lombok.Data; -import lombok.experimental.Accessors; /** * @author mengweijin */ @Data -@Accessors(chain = true) -public class ConfigParameter { +public class Parameters { + + /** + * Absolute path + */ + private String outputDir; private String author; private String templateLocation; - private TemplateType templateType; + private TemplateType templateType = TemplateType.beetl; - /** - * default生成在src/test/java下。 - * sample: com.github.mengweijin.generator - * sample: com/github/mengweijin/generator - */ - private String outputPackage; + private DbInfo dbInfo; private String[] tables; @@ -34,6 +32,4 @@ public class ConfigParameter { private String superServiceImplClass; private String superControllerClass; private String[] superEntityColumns; - - private DbInfo dbInfo; } diff --git a/src/main/java/com/github/mengweijin/generator/config/ConfigFactory.java b/src/main/java/com/github/mengweijin/generator/config/ConfigFactory.java deleted file mode 100644 index 31ca033..0000000 --- a/src/main/java/com/github/mengweijin/generator/config/ConfigFactory.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.github.mengweijin.generator.config; - -import cn.hutool.core.util.StrUtil; -import com.baomidou.mybatisplus.generator.config.DataSourceConfig; -import com.baomidou.mybatisplus.generator.config.GlobalConfig; -import com.baomidou.mybatisplus.generator.config.PackageConfig; -import com.baomidou.mybatisplus.generator.config.StrategyConfig; -import com.baomidou.mybatisplus.generator.config.TemplateConfig; -import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; -import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine; -import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; -import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine; -import com.github.mengweijin.generator.dto.ConfigParameter; -import com.github.mengweijin.generator.dto.DbInfo; -import com.github.mengweijin.generator.engine.BeetlStringTemplateEngine; -import com.github.mengweijin.generator.enums.TemplateType; - -/** - * @author mengweijin - */ -public class ConfigFactory { - - public static GlobalConfig getGlobalConfig(ConfigParameter parameter) { - GlobalConfig globalConfig = new GlobalConfig(); - globalConfig.setOutputDir(parameter.getOutputPackage()); - globalConfig.setAuthor(parameter.getAuthor()); - globalConfig.setOpen(false); - globalConfig.setFileOverride(false); - return globalConfig; - } - - public static DataSourceConfig getDataSourceConfig(ConfigParameter configParameter) { - DbInfo dbInfo = configParameter.getDbInfo(); - DataSourceConfig dataSourceConfig = new DataSourceConfig(); - dataSourceConfig.setUrl(dbInfo.getUrl()); - dataSourceConfig.setDriverName(dbInfo.getDriverName()); - dataSourceConfig.setUsername(dbInfo.getUsername()); - dataSourceConfig.setPassword(dbInfo.getPassword()); - return dataSourceConfig; - } - - public static PackageConfig getPackageConfig(ConfigParameter configParameter) { - PackageConfig packageConfig = new PackageConfig(); - packageConfig.setParent(null); - String moduleName = StrUtil.subAfter(configParameter.getOutputPackage(), StrUtil.SLASH, true); - packageConfig.setModuleName(moduleName); - packageConfig.setEntity(null); - packageConfig.setService(null); - packageConfig.setServiceImpl(null); - packageConfig.setMapper(null); - packageConfig.setXml(null); - packageConfig.setController(null); - packageConfig.setPathInfo(null); - return packageConfig; - } - - /** - * Mybatis-plus自己的模板配置, 不想生成的就设为null。 - * 这里不使用Mybatis-plus自己的,我们使用自定义的 - * - * @param configParameter - * @return - */ - public static TemplateConfig getTemplateConfig(ConfigParameter configParameter) { - TemplateConfig templateConfig = new TemplateConfig(); - templateConfig.setEntity(null); - templateConfig.setEntityKt(null); - templateConfig.setService(null); - templateConfig.setServiceImpl(null); - templateConfig.setMapper(null); - templateConfig.setXml(null); - templateConfig.setController(null); - return templateConfig; - } - - public static StrategyConfig getStrategyConfig(ConfigParameter configParameter) { - StrategyConfig strategy = new StrategyConfig(); - strategy.setNaming(NamingStrategy.underline_to_camel); - strategy.setColumnNaming(NamingStrategy.underline_to_camel); - strategy.setEntityLombokModel(true); - strategy.setRestControllerStyle(true); - - strategy.setSuperEntityClass(configParameter.getSuperEntityClass()); - strategy.setSuperEntityColumns(configParameter.getSuperEntityColumns()); - strategy.setSuperMapperClass(configParameter.getSuperDaoClass()); - strategy.setSuperServiceClass(configParameter.getSuperServiceClass()); - strategy.setSuperServiceImplClass(configParameter.getSuperServiceImplClass()); - strategy.setSuperControllerClass(configParameter.getSuperControllerClass()); - - strategy.setInclude(configParameter.getTables()); - strategy.setControllerMappingHyphenStyle(true); - strategy.setTablePrefix(configParameter.getTablePrefix()); - return strategy; - } - - public static AbstractTemplateEngine getTemplateEngine(ConfigParameter configParameter) { - AbstractTemplateEngine templateEngine; - TemplateType templateType = configParameter.getTemplateType(); - if (TemplateType.velocity == templateType) { - templateEngine = new VelocityTemplateEngine(); - } else if (TemplateType.freemarker == templateType) { - templateEngine = new FreemarkerTemplateEngine(); - } else { - // default beetl - templateEngine = new BeetlStringTemplateEngine(); - } - - return templateEngine; - } - -} diff --git a/src/main/java/com/github/mengweijin/generator/config/FileOutConfigImpl.java b/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java similarity index 81% rename from src/main/java/com/github/mengweijin/generator/config/FileOutConfigImpl.java rename to src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java index 94841e0..360ce9d 100644 --- a/src/main/java/com/github/mengweijin/generator/config/FileOutConfigImpl.java +++ b/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java @@ -1,30 +1,29 @@ package com.github.mengweijin.generator.config; import cn.hutool.core.util.StrUtil; -import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.FileOutConfig; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; - +import com.github.mengweijin.generator.CodeGenerator; import java.io.File; /** * @author mengweijin */ -public class FileOutConfigImpl extends FileOutConfig { +public class CustomerFileOutConfig extends FileOutConfig { - private final AutoGenerator autoGenerator; + private final CodeGenerator codeGenerator; private String templateName; /** * - * @param autoGenerator + * @param codeGenerator * @param templateContent E.g.:controller.java.btl 文件中的字符串内容。 */ - public FileOutConfigImpl(AutoGenerator autoGenerator, String templateContent, String templateName) { + public CustomerFileOutConfig(CodeGenerator codeGenerator, String templateContent, String templateName) { super(templateContent); - this.autoGenerator = autoGenerator; + this.codeGenerator = codeGenerator; this.templateName = templateName; } @@ -36,7 +35,7 @@ public class FileOutConfigImpl extends FileOutConfig { @Override public String outputFile(TableInfo tableInfo) { StringBuilder outputPath = new StringBuilder(); - String outputDir = autoGenerator.getGlobalConfig().getOutputDir(); + String outputDir = codeGenerator.getAutoGenerator().getGlobalConfig().getOutputDir(); outputPath.append(outputDir); if(!outputDir.endsWith(StrUtil.SLASH) && !outputDir.endsWith(StrUtil.BACKSLASH) diff --git a/src/main/java/com/github/mengweijin/generator/dto/DefaultConfigParameter.java b/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java similarity index 45% rename from src/main/java/com/github/mengweijin/generator/dto/DefaultConfigParameter.java rename to src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java index c5a0a09..3314267 100644 --- a/src/main/java/com/github/mengweijin/generator/dto/DefaultConfigParameter.java +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java @@ -1,32 +1,26 @@ -package com.github.mengweijin.generator.dto; +package com.github.mengweijin.generator.config; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.file.FileNameUtil; -import cn.hutool.core.util.ClassLoaderUtil; -import cn.hutool.core.util.ClassUtil; import cn.hutool.core.util.StrUtil; -import cn.hutool.system.SystemUtil; import com.alibaba.fastjson.JSON; -import com.github.mengweijin.generator.enums.TemplateType; +import com.baomidou.mybatisplus.generator.config.DataSourceConfig; +import com.github.mengweijin.generator.CodeGenerator; +import com.github.mengweijin.generator.DbInfo; import com.github.mengweijin.generator.reader.BootFileReaderFactory; -import lombok.Data; -import lombok.EqualsAndHashCode; -import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Resource; -import org.apache.maven.project.MavenProject; + import java.io.File; -import java.lang.reflect.Field; -import java.util.Arrays; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; import java.util.List; -import java.util.Optional; /** * @author mengweijin */ -@Data -@EqualsAndHashCode(callSuper = true) -public class DefaultConfigParameter extends ConfigParameter { +public class DefaultDataSourceConfig extends DataSourceConfig { private static final String[] BOOTSTRAP_FILE = { "bootstrap.yml", @@ -45,61 +39,30 @@ public class DefaultConfigParameter extends ConfigParameter { public static final String SRC_TEST_JAVA = "src/test/java/"; public static final String SRC_MAIN_JAVA = "src/main/java/"; - private MavenSession mavenSession; - - private MavenProject mavenProject; - - private List resourceList; - private File baseDir; + private CodeGenerator codeGenerator; - private File sourceDir; - - public DefaultConfigParameter initDefaultValue() { - this.setAuthor(Optional.ofNullable(this.getAuthor()).orElse(SystemUtil.getUserInfo().getName())); - this.setTemplateType(Optional.ofNullable(this.getTemplateType()).orElse(TemplateType.beetl)); - - String outputPath; - if(StrUtil.isBlank(this.getOutputPackage())) { - outputPath = SRC_TEST_JAVA + "com.github.mengweijin.generator"; - } else { - outputPath = SRC_MAIN_JAVA + this.getOutputPackage(); - } - this.setOutputPackage(StrUtil.replace(outputPath, StrUtil.SLASH, StrUtil.DOT)); - - if (this.getSuperEntityClass() != null && this.getSuperEntityColumns() == null) { - this.setSuperEntityColumns(this.generateDefaultSuperEntityColumns()); - } - - // url/driverName/username/password - DbInfo dbInfo = this.getDbInfo(); - if (dbInfo == null || StrUtil.isBlank(dbInfo.getUrl())) { - this.setDbInfo(this.generateDefaultDbInfo()); - } - - return this; + public DefaultDataSourceConfig(CodeGenerator codeGenerator) { + this.codeGenerator = codeGenerator; + this.init(); } /** - * If the user configured superEntityColumns, the configuration will prevail; - * if not, the default configuration of superEntityColumns will be generated according to the superEntityClass. - * - * @return String[] + * Initialize the default parameter. */ - private String[] generateDefaultSuperEntityColumns() { - try { - ClassLoader classLoader = ClassLoaderUtil.getClassLoader(); - Class cls = Class.forName(this.getSuperEntityClass(), true, classLoader); - Field[] declaredFields = ClassUtil.getDeclaredFields(cls); - return Arrays.stream(declaredFields) - .map(field -> StrUtil.toUnderlineCase(field.getName())).toArray(String[]::new); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - throw new RuntimeException(e); + public void init() { + DbInfo dbInfo = codeGenerator.getParameters().getDbInfo(); + if (dbInfo == null || StrUtil.isBlank(dbInfo.getUrl())) { + dbInfo = this.generateDefaultDbInfo(); } + this.setUrl(dbInfo.getUrl()); + this.setDriverName(dbInfo.getDriverName()); + this.setUsername(dbInfo.getUsername()); + this.setPassword(dbInfo.getPassword()); } private DbInfo generateDefaultDbInfo() { + List resourceList = codeGenerator.getResourceList(); Resource resource = resourceList.stream().filter(res -> res.getDirectory().endsWith("\\resources")).findFirst().get(); //File bootstrapFile = this.getBootFile(resource, BOOTSTRAP_FILE); @@ -135,20 +98,19 @@ public class DefaultConfigParameter extends ConfigParameter { return CollectionUtil.isEmpty(fileList) ? null : fileList.get(0); } + /** + * Override the parent class method + * @return + */ @Override - public String toString() { - return "ConfigParameter(author=" + this.getAuthor() + - ", templateLocation=" + this.getTemplateLocation() + - ", templateType=" + this.getTemplateType() + - ", outputPath=" + this.getOutputPackage() + - ", tables=" + Arrays.deepToString(this.getTables()) + - ", tablePrefix=" + Arrays.deepToString(this.getTablePrefix()) + - ", superEntityClass=" + this.getSuperEntityClass() + - ", superDaoClass=" + this.getSuperDaoClass() + - ", superServiceClass=" + this.getSuperServiceClass() + - ", superServiceImplClass=" + this.getSuperServiceImplClass() + - ", superControllerClass=" + this.getSuperControllerClass() + - ", superEntityColumns=" + Arrays.deepToString(this.getSuperEntityColumns()) + - ", dbInfo=" + this.getDbInfo() + ")"; + public Connection getConn() { + Connection conn; + try { + Class.forName(this.getDriverName(), true, Thread.currentThread().getContextClassLoader()); + conn = DriverManager.getConnection(this.getUrl(), this.getUsername(), this.getPassword()); + } catch (ClassNotFoundException | SQLException e) { + throw new RuntimeException(e); + } + return conn; } } diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java new file mode 100644 index 0000000..3c23c4a --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java @@ -0,0 +1,41 @@ +package com.github.mengweijin.generator.config; + +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.system.SystemUtil; +import com.baomidou.mybatisplus.generator.config.GlobalConfig; +import com.github.mengweijin.generator.CodeGenerator; +import com.github.mengweijin.generator.Parameters; + +import java.io.File; +import java.util.Optional; + +/** + * @author mengweijin + */ +public class DefaultGlobalConfig extends GlobalConfig { + + private CodeGenerator codeGenerator; + + public DefaultGlobalConfig(CodeGenerator codeGenerator) { + this.codeGenerator = codeGenerator; + this.init(); + } + + /** + * Initialize the default parameter. + */ + public void init() { + Parameters parameters = codeGenerator.getParameters(); + File baseDir = codeGenerator.getBaseDir(); + + this.setAuthor(Optional.ofNullable(parameters.getAuthor()).orElse(SystemUtil.getUserInfo().getName())); + + if(StrUtil.isBlank(parameters.getOutputDir())) { + File output = FileUtil.file(baseDir, "target/code-generator/"); + this.setOutputDir(output.getAbsolutePath()); + } else { + this.setOutputDir(parameters.getOutputDir()); + } + } +} diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultInjectionConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultInjectionConfig.java new file mode 100644 index 0000000..4a37aa7 --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultInjectionConfig.java @@ -0,0 +1,27 @@ +package com.github.mengweijin.generator.config; + +import com.baomidou.mybatisplus.generator.InjectionConfig; +import com.github.mengweijin.generator.CodeGenerator; + +import java.util.Map; + +/** + * @author mengweijin + */ +public class DefaultInjectionConfig extends InjectionConfig { + + private CodeGenerator codeGenerator; + + public DefaultInjectionConfig(CodeGenerator codeGenerator) { + this.codeGenerator = codeGenerator; + } + + @Override + public void initMap() { + } + + @Override + public Map prepareObjectMap(Map objectMap) { + return objectMap; + } +} diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java new file mode 100644 index 0000000..05ba0d2 --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java @@ -0,0 +1,33 @@ +package com.github.mengweijin.generator.config; + +import com.baomidou.mybatisplus.generator.config.PackageConfig; +import com.github.mengweijin.generator.CodeGenerator; + +/** + * @author mengweijin + */ +public class DefaultPackageConfig extends PackageConfig { + + private CodeGenerator codeGenerator; + + public DefaultPackageConfig(CodeGenerator codeGenerator) { + this.codeGenerator = codeGenerator; + this.init(); + } + + /** + * Initialize the default parameter. + */ + public void init() { + //String moduleName = StrUtil.subAfter(parameter.getOutputDir(), StrUtil.SLASH, true); + this.setParent("com.github.mengweijin"); + this.setModuleName(null); + this.setEntity(null); + this.setService(null); + this.setServiceImpl(null); + this.setMapper(null); + this.setXml(null); + this.setController(null); + this.setPathInfo(null); + } +} diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultStrategyConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultStrategyConfig.java new file mode 100644 index 0000000..d94064b --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultStrategyConfig.java @@ -0,0 +1,71 @@ +package com.github.mengweijin.generator.config; + +import cn.hutool.core.util.ClassUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.generator.config.StrategyConfig; +import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; +import com.github.mengweijin.generator.CodeGenerator; +import com.github.mengweijin.generator.Parameters; +import java.lang.reflect.Field; +import java.util.Arrays; + +/** + * @author mengweijin + */ +public class DefaultStrategyConfig extends StrategyConfig { + + private CodeGenerator codeGenerator; + + public DefaultStrategyConfig(CodeGenerator codeGenerator) { + this.codeGenerator = codeGenerator; + this.init(); + } + + /** + * Initialize the default parameter. + */ + public void init() { + Parameters parameters = codeGenerator.getParameters(); + + this.setNaming(NamingStrategy.underline_to_camel); + this.setColumnNaming(NamingStrategy.underline_to_camel); + this.setEntityLombokModel(true); + this.setRestControllerStyle(true); + this.setControllerMappingHyphenStyle(true); + this.setEntityTableFieldAnnotationEnable(true); + this.setInclude(parameters.getTables()); + this.setTablePrefix(parameters.getTablePrefix()); + + this.setSuperEntityClass(parameters.getSuperEntityClass()); + + if (this.getSuperEntityClass() != null && this.getSuperEntityColumns() == null) { + this.setSuperEntityColumns(this.generateDefaultSuperEntityColumns()); + } else { + this.setSuperEntityColumns(parameters.getSuperEntityColumns()); + } + + this.setSuperMapperClass(parameters.getSuperDaoClass()); + this.setSuperServiceClass(parameters.getSuperServiceClass()); + this.setSuperServiceImplClass(parameters.getSuperServiceImplClass()); + this.setSuperControllerClass(parameters.getSuperControllerClass()); + } + + /** + * If the user configured superEntityColumns, the configuration will prevail; + * if not, the default configuration of superEntityColumns will be generated according to the superEntityClass. + * + * @return String[] + */ + private String[] generateDefaultSuperEntityColumns() { + try { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + Class cls = Class.forName(this.getSuperEntityClass(), true, classLoader); + Field[] declaredFields = ClassUtil.getDeclaredFields(cls); + return Arrays.stream(declaredFields) + .map(field -> StrUtil.toUnderlineCase(field.getName())).toArray(String[]::new); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultTemplateConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultTemplateConfig.java new file mode 100644 index 0000000..48f711f --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultTemplateConfig.java @@ -0,0 +1,32 @@ +package com.github.mengweijin.generator.config; + +import com.baomidou.mybatisplus.generator.config.TemplateConfig; +import com.github.mengweijin.generator.CodeGenerator; + +/** + * @author mengweijin + */ +public class DefaultTemplateConfig extends TemplateConfig { + + private CodeGenerator codeGenerator; + + public DefaultTemplateConfig(CodeGenerator codeGenerator) { + this.codeGenerator = codeGenerator; + this.init(); + } + + /** + * Initialize the default parameter. + * Mybatis-plus自己的模板配置, 不想生成的就强制设为null。 + * 这里不使用Mybatis-plus自己的,我们使用自定义的 + */ + public void init() { + this.setEntity(null); + this.setEntityKt(null); + this.setService(null); + this.setServiceImpl(null); + this.setMapper(null); + this.setXml(null); + this.setController(null); + } +} diff --git a/src/main/java/com/github/mengweijin/generator/config/InjectionConfigImpl.java b/src/main/java/com/github/mengweijin/generator/config/InjectionConfigImpl.java deleted file mode 100644 index 74a06e5..0000000 --- a/src/main/java/com/github/mengweijin/generator/config/InjectionConfigImpl.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.github.mengweijin.generator.config; - -import cn.hutool.core.util.StrUtil; -import com.baomidou.mybatisplus.generator.AutoGenerator; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.po.TableField; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; -import com.baomidou.mybatisplus.generator.config.rules.IColumnType; -import com.github.mengweijin.generator.dto.ConfigParameter; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * @author mengweijin - */ -public class InjectionConfigImpl extends InjectionConfig { - - private final ConfigParameter parameter; - - private final AutoGenerator autoGenerator; - - public InjectionConfigImpl(ConfigParameter parameter, AutoGenerator autoGenerator) { - this.parameter = parameter; - this.autoGenerator = autoGenerator; - } - - @Override - public void initMap() { - - } - - @Override - public Map prepareObjectMap(Map objectMap) { - Map map = new HashMap<>(); - map.put("author", objectMap.get("author")); - map.put("date", objectMap.get("date")); - map.put("superEntityClassPackage", parameter.getSuperEntityClass()); - map.put("superDaoClassPackage", parameter.getSuperDaoClass()); - map.put("superServiceClassPackage", parameter.getSuperServiceClass()); - map.put("superServiceImplClassPackage", parameter.getSuperServiceImplClass()); - map.put("superControllerClassPackage", parameter.getSuperControllerClass()); - - map.put("superEntityName", StrUtil.subAfter(parameter.getSuperEntityClass(), StrUtil.DOT, true)); - map.put("superDaoName", StrUtil.subAfter(parameter.getSuperDaoClass(), StrUtil.DOT, true)); - map.put("superServiceName", StrUtil.subAfter(parameter.getSuperServiceClass(), StrUtil.DOT, true)); - map.put("superServiceImplName", StrUtil.subAfter(parameter.getSuperServiceImplClass(), StrUtil.DOT, true)); - map.put("superControllerName", StrUtil.subAfter(parameter.getSuperControllerClass(), StrUtil.DOT, true)); - - map.put("entityName", objectMap.get("entity")); - map.put("entityVariableName", StrUtil.lowerFirst(String.valueOf(objectMap.get("entity")))); - - // src.test.java.com.github.mengweijin.generator - map.put("basePackage", StrUtil.subAfter(parameter.getOutputPackage(), "java.", false)); - map.put("moduleName", autoGenerator.getPackageInfo().getModuleName()); - - map.put("table", objectMap.get("table")); - - map.put("fieldImportPackages", handleFieldImportPackage((TableInfo) objectMap.get("table"))); - map.put("idPropertyType", handleIdPropertyType((TableInfo) objectMap.get("table"))); - map.put("idField", handleIdField((TableInfo) objectMap.get("table"))); - map.put("allFieldList", handleAllFieldList((TableInfo) objectMap.get("table"))); - - return map; - } - - private Set handleFieldImportPackage(TableInfo tableInfo) { - Set set = new HashSet<>(); - tableInfo.getFields().forEach(tableField -> { - IColumnType columnType = tableField.getColumnType(); - if (columnType.getPkg() != null) { - set.add(columnType.getPkg()); - } - }); - - return set; - } - - private String handleIdPropertyType(TableInfo tableInfo) { - Optional optional = tableInfo.getFields().stream() - .filter(TableField::isKeyFlag) - .map(tableField -> tableField.getColumnType().getType()).findFirst(); - return optional.orElse(DbColumnType.LONG.getType()); - } - - private TableField handleIdField(TableInfo tableInfo) { - Optional optional = tableInfo.getFields().stream().filter(TableField::isKeyFlag).findFirst(); - return optional.orElse(new TableField()); - } - - private List handleAllFieldList(TableInfo tableInfo) { - List fields = tableInfo.getFields(); - List commonFields = tableInfo.getCommonFields(); - List allFields = new ArrayList<>(); - allFields.addAll(fields); - allFields.addAll(commonFields); - return allFields; - } -} diff --git a/src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java b/src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java new file mode 100644 index 0000000..34e5450 --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java @@ -0,0 +1,34 @@ +package com.github.mengweijin.generator.factory; + +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.github.mengweijin.generator.enums.TemplateType; +import java.util.HashMap; + +/** + * @author mengweijin + */ +public class TemplateEngineFactory { + + public static final HashMap map = new HashMap<>(3); + + static { + map.put(TemplateType.beetl, new BeetlTemplateEngine()); + map.put(TemplateType.freemarker, new FreemarkerTemplateEngine()); + map.put(TemplateType.velocity, new VelocityTemplateEngine()); + } + + private TemplateEngineFactory() { + } + + public static AbstractTemplateEngine getTemplateEngine(TemplateType templateType) { + AbstractTemplateEngine engine = map.get(templateType); + if(engine == null) { + throw new RuntimeException("TemplateType can't be null!"); + } + + return engine; + } +} diff --git a/src/main/java/com/github/mengweijin/generator/mojo/AbstractGeneratorMojo.java b/src/main/java/com/github/mengweijin/generator/mojo/AbstractGeneratorMojo.java index b25a1f5..2c88035 100644 --- a/src/main/java/com/github/mengweijin/generator/mojo/AbstractGeneratorMojo.java +++ b/src/main/java/com/github/mengweijin/generator/mojo/AbstractGeneratorMojo.java @@ -1,9 +1,8 @@ package com.github.mengweijin.generator.mojo; -import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.JarClassLoader; -import com.github.mengweijin.generator.dto.ConfigParameter; -import com.github.mengweijin.generator.dto.DefaultConfigParameter; +import com.github.mengweijin.generator.CodeGenerator; +import com.github.mengweijin.generator.Parameters; import lombok.Getter; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Resource; @@ -25,7 +24,7 @@ import java.util.Optional; public abstract class AbstractGeneratorMojo extends AbstractMojo { @Parameter - private ConfigParameter configParameter; + private Parameters parameters; @Parameter(defaultValue = "${project}") private MavenProject project; @@ -51,19 +50,18 @@ public abstract class AbstractGeneratorMojo extends AbstractMojo { @Parameter(defaultValue = "${session}", readonly = true) private MavenSession session; - protected DefaultConfigParameter getGeneratorConfig() { - this.loadParentProjectClassToSystemClassLoader(); - this.configParameter = Optional.ofNullable(this.configParameter).orElse(new ConfigParameter()); - DefaultConfigParameter defaultConfigParameter = BeanUtil.copyProperties(configParameter, DefaultConfigParameter.class); - defaultConfigParameter.setMavenSession(this.getSession()); - defaultConfigParameter.setMavenProject(this.getProject()); - defaultConfigParameter.setResourceList(this.getResources()); - defaultConfigParameter.setBaseDir(this.baseDir); - defaultConfigParameter.setSourceDir(this.sourceDir); - return defaultConfigParameter; + protected CodeGenerator getCodeGenerator() { + this.loadParentProjectClassToJarClassLoader(); + this.parameters = Optional.ofNullable(this.parameters).orElse(new Parameters()); + CodeGenerator codeGenerator = new CodeGenerator(); + codeGenerator.setParameters(this.parameters); + codeGenerator.setResourceList(this.getResources()); + codeGenerator.setBaseDir(this.baseDir); + codeGenerator.setSourceDir(this.sourceDir); + return codeGenerator; } - protected void loadParentProjectClassToSystemClassLoader() { + protected void loadParentProjectClassToApplicationClassLoader() { URLClassLoader urlLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); try { @@ -92,7 +90,6 @@ public abstract class AbstractGeneratorMojo extends AbstractMojo { } JarClassLoader jarClassLoader = new JarClassLoader(urls); Thread.currentThread().setContextClassLoader(jarClassLoader); - } catch (Exception e) { getLog().error("Load Parent Project Class to ClassLoader Error."); throw new RuntimeException(e); diff --git a/src/main/java/com/github/mengweijin/generator/mojo/JpaGeneratorMojo.java b/src/main/java/com/github/mengweijin/generator/mojo/JpaGeneratorMojo.java index 7700a85..4c99d71 100644 --- a/src/main/java/com/github/mengweijin/generator/mojo/JpaGeneratorMojo.java +++ b/src/main/java/com/github/mengweijin/generator/mojo/JpaGeneratorMojo.java @@ -1,8 +1,7 @@ package com.github.mengweijin.generator.mojo; -import com.github.mengweijin.generator.dto.DefaultConfigParameter; +import com.github.mengweijin.generator.CodeGenerator; import com.github.mengweijin.generator.enums.Template; -import com.github.mengweijin.generator.main.CodeGenerator; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; @@ -14,17 +13,15 @@ import org.apache.maven.plugins.annotations.ResolutionScope; @Mojo(name = "jpa", requiresDependencyResolution = ResolutionScope.COMPILE) public class JpaGeneratorMojo extends AbstractGeneratorMojo { + private static final String JpaRepository = "org.springframework.data.jpa.repository.JpaRepository"; + @Override public void execute() throws MojoExecutionException, MojoFailureException { try { - DefaultConfigParameter parameter = this.getGeneratorConfig(); - parameter.initDefaultValue(); - parameter.setTemplateLocation(Template.JPA.getPath()); - parameter.setSuperDaoClass("org.springframework.data.jpa.repository.JpaRepository"); - - System.out.println("DefaultConfigParameter: " + parameter); - - new CodeGenerator(parameter).run(); + CodeGenerator codeGenerator = this.getCodeGenerator(); + codeGenerator.getParameters().setTemplateLocation(Template.JPA.getPath()); + codeGenerator.getParameters().setSuperDaoClass(JpaRepository); + codeGenerator.run(); } catch (Exception e) { getLog().error(e); throw new RuntimeException(e); diff --git a/src/main/java/com/github/mengweijin/generator/mojo/MybatisGeneratorMojo.java b/src/main/java/com/github/mengweijin/generator/mojo/MybatisGeneratorMojo.java index 794c343..d4798c3 100644 --- a/src/main/java/com/github/mengweijin/generator/mojo/MybatisGeneratorMojo.java +++ b/src/main/java/com/github/mengweijin/generator/mojo/MybatisGeneratorMojo.java @@ -1,8 +1,7 @@ package com.github.mengweijin.generator.mojo; -import com.github.mengweijin.generator.dto.DefaultConfigParameter; +import com.github.mengweijin.generator.CodeGenerator; import com.github.mengweijin.generator.enums.Template; -import com.github.mengweijin.generator.main.CodeGenerator; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; @@ -16,13 +15,9 @@ public class MybatisGeneratorMojo extends AbstractGeneratorMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { try { - DefaultConfigParameter defaultConfigParameter = this.getGeneratorConfig(); - defaultConfigParameter.initDefaultValue(); - defaultConfigParameter.setTemplateLocation(Template.MYBATIS.getPath()); - - System.out.println("DefaultConfigParameter: " + defaultConfigParameter); - - new CodeGenerator(defaultConfigParameter).run(); + CodeGenerator codeGenerator = this.getCodeGenerator(); + codeGenerator.getParameters().setTemplateLocation(Template.MYBATIS.getPath()); + codeGenerator.run(); } catch (Exception e) { getLog().error(e); throw new RuntimeException(e); diff --git a/src/main/java/com/github/mengweijin/generator/mojo/MybatisPlusGeneratorMojo.java b/src/main/java/com/github/mengweijin/generator/mojo/MybatisPlusGeneratorMojo.java index e28e17c..cdb5ae2 100644 --- a/src/main/java/com/github/mengweijin/generator/mojo/MybatisPlusGeneratorMojo.java +++ b/src/main/java/com/github/mengweijin/generator/mojo/MybatisPlusGeneratorMojo.java @@ -1,8 +1,7 @@ package com.github.mengweijin.generator.mojo; -import com.github.mengweijin.generator.dto.DefaultConfigParameter; +import com.github.mengweijin.generator.CodeGenerator; import com.github.mengweijin.generator.enums.Template; -import com.github.mengweijin.generator.main.CodeGenerator; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; @@ -13,19 +12,20 @@ import org.apache.maven.plugins.annotations.ResolutionScope; */ @Mojo(name = "mybatis-plus", requiresDependencyResolution = ResolutionScope.COMPILE) public class MybatisPlusGeneratorMojo extends AbstractGeneratorMojo { + + private static final String BaseMapper = "com.baomidou.mybatisplus.core.mapper.BaseMapper"; + private static final String IService = "com.baomidou.mybatisplus.extension.service.IService"; + private static final String ServiceImpl = "com.baomidou.mybatisplus.extension.service.impl.ServiceImpl"; + @Override public void execute() throws MojoExecutionException, MojoFailureException { try { - DefaultConfigParameter parameter = this.getGeneratorConfig(); - parameter.initDefaultValue(); - parameter.setTemplateLocation(Template.MYBATIS_PLUS.getPath()); - parameter.setSuperDaoClass("com.baomidou.mybatisplus.core.mapper.BaseMapper"); - parameter.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService"); - parameter.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl"); - - System.out.println("DefaultConfigParameter: " + parameter); - - new CodeGenerator(parameter).run(); + CodeGenerator codeGenerator = this.getCodeGenerator(); + codeGenerator.getParameters().setTemplateLocation(Template.MYBATIS_PLUS.getPath()); + codeGenerator.getParameters().setSuperDaoClass(BaseMapper); + codeGenerator.getParameters().setSuperServiceClass(IService); + codeGenerator.getParameters().setSuperServiceImplClass(ServiceImpl); + codeGenerator.run(); } catch (Exception e) { getLog().error(e); throw new RuntimeException(e); diff --git a/src/main/java/com/github/mengweijin/generator/reader/BootFileReader.java b/src/main/java/com/github/mengweijin/generator/reader/BootFileReader.java index 2868181..e5c1540 100644 --- a/src/main/java/com/github/mengweijin/generator/reader/BootFileReader.java +++ b/src/main/java/com/github/mengweijin/generator/reader/BootFileReader.java @@ -1,6 +1,6 @@ package com.github.mengweijin.generator.reader; -import com.github.mengweijin.generator.dto.DbInfo; +import com.github.mengweijin.generator.DbInfo; import java.io.File; diff --git a/src/main/java/com/github/mengweijin/generator/reader/BootFileReaderFactory.java b/src/main/java/com/github/mengweijin/generator/reader/BootFileReaderFactory.java index d24b567..07a29e7 100644 --- a/src/main/java/com/github/mengweijin/generator/reader/BootFileReaderFactory.java +++ b/src/main/java/com/github/mengweijin/generator/reader/BootFileReaderFactory.java @@ -2,8 +2,7 @@ package com.github.mengweijin.generator.reader; import cn.hutool.core.io.file.FileNameUtil; import cn.hutool.core.util.EnumUtil; -import com.github.mengweijin.generator.dto.DbInfo; -import lombok.extern.slf4j.Slf4j; +import com.github.mengweijin.generator.DbInfo; import java.io.File; import java.util.HashMap; diff --git a/src/main/java/com/github/mengweijin/generator/reader/PropertiesBootFileReader.java b/src/main/java/com/github/mengweijin/generator/reader/PropertiesBootFileReader.java index bb603c7..c666890 100644 --- a/src/main/java/com/github/mengweijin/generator/reader/PropertiesBootFileReader.java +++ b/src/main/java/com/github/mengweijin/generator/reader/PropertiesBootFileReader.java @@ -2,7 +2,7 @@ package com.github.mengweijin.generator.reader; import cn.hutool.core.util.StrUtil; import cn.hutool.setting.dialect.Props; -import com.github.mengweijin.generator.dto.DbInfo; +import com.github.mengweijin.generator.DbInfo; import java.io.File; import java.net.MalformedURLException; diff --git a/src/main/java/com/github/mengweijin/generator/reader/YamlBootFileReader.java b/src/main/java/com/github/mengweijin/generator/reader/YamlBootFileReader.java index bfe8cdc..5757e4f 100644 --- a/src/main/java/com/github/mengweijin/generator/reader/YamlBootFileReader.java +++ b/src/main/java/com/github/mengweijin/generator/reader/YamlBootFileReader.java @@ -1,7 +1,7 @@ package com.github.mengweijin.generator.reader; import com.alibaba.fastjson.JSONPath; -import com.github.mengweijin.generator.dto.DbInfo; +import com.github.mengweijin.generator.DbInfo; import com.github.mengweijin.generator.util.YamlUtils; import java.io.File; diff --git a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java index 045ade8..ded44b0 100644 --- a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java +++ b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java @@ -4,11 +4,10 @@ import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; -import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.FileOutConfig; -import com.github.mengweijin.generator.config.FileOutConfigImpl; -import com.github.mengweijin.generator.dto.DefaultConfigParameter; - +import com.github.mengweijin.generator.config.CustomerFileOutConfig; +import com.github.mengweijin.generator.CodeGenerator; +import com.github.mengweijin.generator.Parameters; import java.io.File; import java.net.URL; import java.util.ArrayList; @@ -22,44 +21,47 @@ import java.util.jar.JarFile; */ public class FileOutConfigUtils { - public static List loadTemplatesToGetFileOutConfig(DefaultConfigParameter parameter, AutoGenerator autoGenerator) { + public static List loadTemplatesToGetFileOutConfig(CodeGenerator codeGenerator) { + Parameters parameters = codeGenerator.getParameters(); // 自定义输出配置 List fileOutConfigList = null; - URL url = Thread.currentThread().getContextClassLoader().getResource(parameter.getTemplateLocation()); + URL url = Thread.currentThread().getContextClassLoader().getResource(parameters.getTemplateLocation()); if (URLUtil.isFileURL(url)) { - fileOutConfigList = FileOutConfigUtils.resolveByFileSystem(autoGenerator, parameter); + fileOutConfigList = FileOutConfigUtils.resolveByFileSystem(codeGenerator); } else if (URLUtil.isJarURL(url)) { JarFile jarFile = URLUtil.getJarFile(url); - fileOutConfigList = FileOutConfigUtils.resolveByJarFile(autoGenerator, parameter, jarFile); + fileOutConfigList = FileOutConfigUtils.resolveByJarFile(codeGenerator, jarFile); } return fileOutConfigList; } - private static List resolveByFileSystem(AutoGenerator autoGenerator, DefaultConfigParameter parameter) { + private static List resolveByFileSystem(CodeGenerator codeGenerator) { List fileOutConfigList = new ArrayList<>(); + Parameters parameters = codeGenerator.getParameters(); - List fileList = FileUtil.loopFiles(parameter.getTemplateLocation(), - file -> file.isFile() && file.getName().toLowerCase().endsWith(parameter.getTemplateType().name())); + List fileList = FileUtil.loopFiles(parameters.getTemplateLocation(), + file -> file.isFile() && file.getName().toLowerCase().endsWith(parameters.getTemplateType().name())); if (CollectionUtil.isEmpty(fileList)) { - throw new RuntimeException("No template files found in location " + parameter.getTemplateLocation()); + throw new RuntimeException("No template files found in location " + parameters.getTemplateLocation()); } - String message = "Found " + fileList.size() + "template files in location " + parameter.getTemplateLocation(); + String message = "Found " + fileList.size() + "template files in location " + parameters.getTemplateLocation(); System.out.println(message); fileList.forEach(file -> { // 自定义配置会被优先输出 - String templatePath = parameter.getBaseDir().getAbsolutePath() + File.separator + parameter.getTemplateLocation() + file.getName(); + String templatePath = codeGenerator.getBaseDir().getAbsolutePath() + File.separator + parameters.getTemplateLocation() + file.getName(); String templateName = file.getName(); - FileOutConfig fileOutConfig = new FileOutConfigImpl(autoGenerator, templatePath, templateName); + FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, templatePath, templateName); fileOutConfigList.add(fileOutConfig); }); return fileOutConfigList; } - private static List resolveByJarFile(AutoGenerator autoGenerator, DefaultConfigParameter parameter, JarFile jarFile) { + private static List resolveByJarFile(CodeGenerator codeGenerator, JarFile jarFile) { + Parameters parameters = codeGenerator.getParameters(); List fileOutConfigList = new ArrayList<>(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); @@ -67,10 +69,10 @@ public class FileOutConfigUtils { String jarEntryName; while (enumeration.hasMoreElements()) { jarEntryName = enumeration.nextElement().getName(); - if (jarEntryName.startsWith(parameter.getTemplateLocation()) && !jarEntryName.endsWith("/")) { + if (jarEntryName.startsWith(parameters.getTemplateLocation()) && !jarEntryName.endsWith("/")) { String templateContent = FileUtil.readString(classLoader.getResource(jarEntryName), "UTF-8"); String templateName = StrUtil.subAfter(jarEntryName, StrUtil.SLASH, true); - FileOutConfig fileOutConfig = new FileOutConfigImpl(autoGenerator, templateContent, templateName); + FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, templateContent, templateName); fileOutConfigList.add(fileOutConfig); } } -- Gitee From 2debabf8b39ae284778f4b9f218d03a2fec20527 Mon Sep 17 00:00:00 2001 From: mengweijin <1002284406@qq.com> Date: Tue, 22 Dec 2020 23:35:41 +0800 Subject: [PATCH 2/7] update --- .../mengweijin/generator/CodeGenerator.java | 12 +++-- .../config/CustomerFileOutConfig.java | 14 +++-- .../generator/config/DefaultGlobalConfig.java | 2 + .../engine/BeetlStringTemplateEngine.java | 4 +- .../CustomerAbstractTemplateEngine.java | 54 +++++++++++++++++++ .../generator/util/FileOutConfigUtils.java | 12 ++--- .../mengweijin/generator/util/YamlUtils.java | 4 +- 7 files changed, 77 insertions(+), 25 deletions(-) create mode 100644 src/main/java/com/github/mengweijin/generator/engine/CustomerAbstractTemplateEngine.java diff --git a/src/main/java/com/github/mengweijin/generator/CodeGenerator.java b/src/main/java/com/github/mengweijin/generator/CodeGenerator.java index 575ccce..535f22d 100644 --- a/src/main/java/com/github/mengweijin/generator/CodeGenerator.java +++ b/src/main/java/com/github/mengweijin/generator/CodeGenerator.java @@ -1,5 +1,7 @@ package com.github.mengweijin.generator; +import cn.hutool.core.io.FileUtil; +import cn.hutool.system.SystemUtil; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.FileOutConfig; @@ -22,6 +24,8 @@ import java.util.List; @Data public class CodeGenerator { + public static final String TMP_DIR = SystemUtil.get(SystemUtil.TMPDIR) + "code-generator/"; + private AutoGenerator autoGenerator; private Parameters parameters; @@ -42,21 +46,19 @@ public class CodeGenerator { autoGenerator.setPackageInfo(new DefaultPackageConfig(this)); // Mybatis-plus自己的模板配置 autoGenerator.setTemplate(new DefaultTemplateConfig(this)); - // 自定义配置, 会被优先输出 InjectionConfig injectionConfig = new DefaultInjectionConfig(this); List fileOutConfigList = FileOutConfigUtils.loadTemplatesToGetFileOutConfig(this); - - // TODO check file exits. injectionConfig.setFileOutConfigList(fileOutConfigList); autoGenerator.setCfg(injectionConfig); - // 策略配置 autoGenerator.setStrategy(new DefaultStrategyConfig(this)); // 模板引擎 autoGenerator.setTemplateEngine(TemplateEngineFactory.getTemplateEngine(this.parameters.getTemplateType())); autoGenerator.execute(); - } + // clean TMP folder + FileUtil.del(FileUtil.file(TMP_DIR)); + } } diff --git a/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java b/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java index 360ce9d..2299358 100644 --- a/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java +++ b/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java @@ -14,23 +14,20 @@ public class CustomerFileOutConfig extends FileOutConfig { private final CodeGenerator codeGenerator; - private String templateName; - /** * * @param codeGenerator - * @param templateContent E.g.:controller.java.btl 文件中的字符串内容。 + * @param templatePath 绝对全路径 */ - public CustomerFileOutConfig(CodeGenerator codeGenerator, String templateContent, String templateName) { - super(templateContent); + public CustomerFileOutConfig(CodeGenerator codeGenerator, String templatePath) { + super(templatePath); this.codeGenerator = codeGenerator; - this.templateName = templateName; } /** * * @param tableInfo - * @return target/code-generator/controller/SysUserController.java + * @return 全路径名 */ @Override public String outputFile(TableInfo tableInfo) { @@ -43,7 +40,8 @@ public class CustomerFileOutConfig extends FileOutConfig { outputPath.append(File.separator); } StringBuilder componentName = new StringBuilder(); - String[] packageHierarchy = this.templateName.split("\\."); + String templateName = StrUtil.subAfter(this.getTemplatePath(), StrUtil.SLASH, true); + String[] packageHierarchy = templateName.split("\\."); if ("entity".equalsIgnoreCase(packageHierarchy[0])) { outputPath.append(packageHierarchy[0]).append(File.separator); } else { diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java index 3c23c4a..2f0ff75 100644 --- a/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java @@ -37,5 +37,7 @@ public class DefaultGlobalConfig extends GlobalConfig { } else { this.setOutputDir(parameters.getOutputDir()); } + + this.setOpen(false); } } diff --git a/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java b/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java index 580d438..0c7d61d 100644 --- a/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java +++ b/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java @@ -2,12 +2,10 @@ package com.github.mengweijin.generator.engine; import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder; import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine; -import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine; import org.beetl.core.Configuration; import org.beetl.core.GroupTemplate; import org.beetl.core.Template; import org.beetl.core.resource.StringTemplateResourceLoader; - import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; @@ -15,7 +13,7 @@ import java.util.Map; /** * @author mengweijin */ -public class BeetlStringTemplateEngine extends BeetlTemplateEngine { +public class BeetlStringTemplateEngine extends CustomerAbstractTemplateEngine { private GroupTemplate groupTemplate; diff --git a/src/main/java/com/github/mengweijin/generator/engine/CustomerAbstractTemplateEngine.java b/src/main/java/com/github/mengweijin/generator/engine/CustomerAbstractTemplateEngine.java new file mode 100644 index 0000000..de40359 --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/engine/CustomerAbstractTemplateEngine.java @@ -0,0 +1,54 @@ +package com.github.mengweijin.generator.engine; + +import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; +import com.baomidou.mybatisplus.generator.InjectionConfig; +import com.baomidou.mybatisplus.generator.config.FileOutConfig; +import com.baomidou.mybatisplus.generator.config.TemplateConfig; +import com.baomidou.mybatisplus.generator.config.po.TableInfo; +import com.baomidou.mybatisplus.generator.config.rules.FileType; +import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine; + +import java.util.List; +import java.util.Map; + +/** + * @author mengweijin + */ +public abstract class CustomerAbstractTemplateEngine extends AbstractTemplateEngine { + + @Override + public AbstractTemplateEngine batchOutput() { + try { + List tableInfoList = getConfigBuilder().getTableInfoList(); + for (TableInfo tableInfo : tableInfoList) { + Map objectMap = getObjectMap(tableInfo); + Map pathInfo = getConfigBuilder().getPathInfo(); + TemplateConfig template = getConfigBuilder().getTemplate(); + // 自定义内容 + InjectionConfig injectionConfig = getConfigBuilder().getInjectionConfig(); + if (null != injectionConfig) { + injectionConfig.initTableMap(tableInfo); + objectMap.put("cfg", injectionConfig.getMap()); + List focList = injectionConfig.getFileOutConfigList(); + if (CollectionUtils.isNotEmpty(focList)) { + String output; + for (FileOutConfig foc : focList) { + output = foc.outputFile(tableInfo); + if (isCreate(FileType.OTHER, output)) { + writer(objectMap, foc.getTemplatePath(), output); + } else { + System.out.println("Warning: File already exists when generated! " + output); + } + } + } else { + + } + } + } + } catch (Exception e) { + System.err.println("Exception: Can't create file, please check the configuration! " + e.toString()); + logger.error("Can't create file, please check the configuration!", e); + } + return this; + } +} diff --git a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java index ded44b0..a78106d 100644 --- a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java +++ b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java @@ -2,12 +2,11 @@ package com.github.mengweijin.generator.util; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; -import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; import com.baomidou.mybatisplus.generator.config.FileOutConfig; -import com.github.mengweijin.generator.config.CustomerFileOutConfig; import com.github.mengweijin.generator.CodeGenerator; import com.github.mengweijin.generator.Parameters; +import com.github.mengweijin.generator.config.CustomerFileOutConfig; import java.io.File; import java.net.URL; import java.util.ArrayList; @@ -52,14 +51,14 @@ public class FileOutConfigUtils { fileList.forEach(file -> { // 自定义配置会被优先输出 String templatePath = codeGenerator.getBaseDir().getAbsolutePath() + File.separator + parameters.getTemplateLocation() + file.getName(); - String templateName = file.getName(); - FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, templatePath, templateName); + FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, templatePath); fileOutConfigList.add(fileOutConfig); }); return fileOutConfigList; } + // TODO 在MOJO入口处,对jar包里面的模板文件先做拷贝到文件系统,然后统一使用文件系统绝对路径。就可以删除这个方法了 private static List resolveByJarFile(CodeGenerator codeGenerator, JarFile jarFile) { Parameters parameters = codeGenerator.getParameters(); List fileOutConfigList = new ArrayList<>(); @@ -70,9 +69,8 @@ public class FileOutConfigUtils { while (enumeration.hasMoreElements()) { jarEntryName = enumeration.nextElement().getName(); if (jarEntryName.startsWith(parameters.getTemplateLocation()) && !jarEntryName.endsWith("/")) { - String templateContent = FileUtil.readString(classLoader.getResource(jarEntryName), "UTF-8"); - String templateName = StrUtil.subAfter(jarEntryName, StrUtil.SLASH, true); - FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, templateContent, templateName); + String templatePath = FileUtil.readString(classLoader.getResource(jarEntryName), "UTF-8"); + FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, templatePath); fileOutConfigList.add(fileOutConfig); } } diff --git a/src/main/java/com/github/mengweijin/generator/util/YamlUtils.java b/src/main/java/com/github/mengweijin/generator/util/YamlUtils.java index 051fb85..d960744 100644 --- a/src/main/java/com/github/mengweijin/generator/util/YamlUtils.java +++ b/src/main/java/com/github/mengweijin/generator/util/YamlUtils.java @@ -3,7 +3,7 @@ package com.github.mengweijin.generator.util; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.StrUtil; -import cn.hutool.system.SystemUtil; +import com.github.mengweijin.generator.CodeGenerator; import org.yaml.snakeyaml.Yaml; import java.io.File; @@ -30,7 +30,7 @@ public class YamlUtils { } return line; }).collect(Collectors.toList()); - File tempFile = FileUtil.file(SystemUtil.get(SystemUtil.TMPDIR) + "code-generator/" + file.getName()); + File tempFile = FileUtil.file(CodeGenerator.TMP_DIR + file.getName()); FileUtil.writeLines(lineCollect, tempFile, StandardCharsets.UTF_8); Yaml yaml = new Yaml(); -- Gitee From 8575a79e7884c544bbfb4f41bc1fb1a301eb28e4 Mon Sep 17 00:00:00 2001 From: mengweijin <1002284406@qq.com> Date: Wed, 23 Dec 2020 21:52:34 +0800 Subject: [PATCH 3/7] update --- .../mengweijin/generator/CodeGenerator.java | 9 ++- .../config/CustomerFileOutConfig.java | 19 +++--- .../config/DefaultDataSourceConfig.java | 2 - .../generator/mojo/AbstractGeneratorMojo.java | 43 ++++++++++++++ .../mojo/MybatisPlusGeneratorMojo.java | 5 +- .../generator/util/FileOutConfigUtils.java | 58 +++---------------- 6 files changed, 72 insertions(+), 64 deletions(-) diff --git a/src/main/java/com/github/mengweijin/generator/CodeGenerator.java b/src/main/java/com/github/mengweijin/generator/CodeGenerator.java index 535f22d..e7bed75 100644 --- a/src/main/java/com/github/mengweijin/generator/CodeGenerator.java +++ b/src/main/java/com/github/mengweijin/generator/CodeGenerator.java @@ -4,17 +4,17 @@ import cn.hutool.core.io.FileUtil; import cn.hutool.system.SystemUtil; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.FileOutConfig; -import com.github.mengweijin.generator.config.DefaultInjectionConfig; -import com.github.mengweijin.generator.util.FileOutConfigUtils; import com.github.mengweijin.generator.config.DefaultDataSourceConfig; import com.github.mengweijin.generator.config.DefaultGlobalConfig; +import com.github.mengweijin.generator.config.DefaultInjectionConfig; import com.github.mengweijin.generator.config.DefaultPackageConfig; import com.github.mengweijin.generator.config.DefaultStrategyConfig; import com.github.mengweijin.generator.config.DefaultTemplateConfig; import com.github.mengweijin.generator.factory.TemplateEngineFactory; +import com.github.mengweijin.generator.util.FileOutConfigUtils; import lombok.Data; import org.apache.maven.model.Resource; + import java.io.File; import java.util.List; @@ -48,8 +48,7 @@ public class CodeGenerator { autoGenerator.setTemplate(new DefaultTemplateConfig(this)); // 自定义配置, 会被优先输出 InjectionConfig injectionConfig = new DefaultInjectionConfig(this); - List fileOutConfigList = FileOutConfigUtils.loadTemplatesToGetFileOutConfig(this); - injectionConfig.setFileOutConfigList(fileOutConfigList); + injectionConfig.setFileOutConfigList(FileOutConfigUtils.loadTemplatesToGetFileOutConfig(this)); autoGenerator.setCfg(injectionConfig); // 策略配置 autoGenerator.setStrategy(new DefaultStrategyConfig(this)); diff --git a/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java b/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java index 2299358..6a67f47 100644 --- a/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java +++ b/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java @@ -1,7 +1,9 @@ package com.github.mengweijin.generator.config; +import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.generator.config.FileOutConfig; +import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.github.mengweijin.generator.CodeGenerator; @@ -31,17 +33,20 @@ public class CustomerFileOutConfig extends FileOutConfig { */ @Override public String outputFile(TableInfo tableInfo) { - StringBuilder outputPath = new StringBuilder(); String outputDir = codeGenerator.getAutoGenerator().getGlobalConfig().getOutputDir(); - outputPath.append(outputDir); - if(!outputDir.endsWith(StrUtil.SLASH) - && !outputDir.endsWith(StrUtil.BACKSLASH) - && !outputDir.endsWith(StrUtil.DOT)) { + StringBuilder outputPath = new StringBuilder(outputDir); + + if(!outputDir.endsWith(StrUtil.SLASH) && !outputDir.endsWith(StrUtil.BACKSLASH)) { outputPath.append(File.separator); } + PackageConfig packageConfig = codeGenerator.getAutoGenerator().getPackageInfo(); + if(!StrUtil.isBlank(packageConfig.getParent())) { + outputPath.append(packageConfig.getParent()).append(File.separator); + } + StringBuilder componentName = new StringBuilder(); - String templateName = StrUtil.subAfter(this.getTemplatePath(), StrUtil.SLASH, true); - String[] packageHierarchy = templateName.split("\\."); + File templateFile = FileUtil.file(this.getTemplatePath()); + String[] packageHierarchy = templateFile.getName().split("\\."); if ("entity".equalsIgnoreCase(packageHierarchy[0])) { outputPath.append(packageHierarchy[0]).append(File.separator); } else { diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java index 3314267..50406ea 100644 --- a/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java @@ -10,7 +10,6 @@ import com.github.mengweijin.generator.CodeGenerator; import com.github.mengweijin.generator.DbInfo; import com.github.mengweijin.generator.reader.BootFileReaderFactory; import org.apache.maven.model.Resource; - import java.io.File; import java.sql.Connection; import java.sql.DriverManager; @@ -64,7 +63,6 @@ public class DefaultDataSourceConfig extends DataSourceConfig { private DbInfo generateDefaultDbInfo() { List resourceList = codeGenerator.getResourceList(); Resource resource = resourceList.stream().filter(res -> res.getDirectory().endsWith("\\resources")).findFirst().get(); - //File bootstrapFile = this.getBootFile(resource, BOOTSTRAP_FILE); File applicationFile = this.getBootFile(resource, APPLICATION_FILE); if (applicationFile == null) { diff --git a/src/main/java/com/github/mengweijin/generator/mojo/AbstractGeneratorMojo.java b/src/main/java/com/github/mengweijin/generator/mojo/AbstractGeneratorMojo.java index 2c88035..6484ef4 100644 --- a/src/main/java/com/github/mengweijin/generator/mojo/AbstractGeneratorMojo.java +++ b/src/main/java/com/github/mengweijin/generator/mojo/AbstractGeneratorMojo.java @@ -1,6 +1,10 @@ package com.github.mengweijin.generator.mojo; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.io.IoUtil; import cn.hutool.core.lang.JarClassLoader; +import cn.hutool.core.util.StrUtil; +import cn.hutool.core.util.URLUtil; import com.github.mengweijin.generator.CodeGenerator; import com.github.mengweijin.generator.Parameters; import lombok.Getter; @@ -11,11 +15,16 @@ import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import java.io.File; +import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; +import java.util.Enumeration; import java.util.List; import java.util.Optional; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; /** * @author mengweijin @@ -52,6 +61,7 @@ public abstract class AbstractGeneratorMojo extends AbstractMojo { protected CodeGenerator getCodeGenerator() { this.loadParentProjectClassToJarClassLoader(); + this.copyTemplateFolderToJavaTmp("templates/"); this.parameters = Optional.ofNullable(this.parameters).orElse(new Parameters()); CodeGenerator codeGenerator = new CodeGenerator(); codeGenerator.setParameters(this.parameters); @@ -95,4 +105,37 @@ public abstract class AbstractGeneratorMojo extends AbstractMojo { throw new RuntimeException(e); } } + + /** + * + * @param classPathResource "templates/" + */ + private void copyTemplateFolderToJavaTmp(String classPathResource) { + File tmpFile; + JarFile jarFile = null; + InputStream inputStream = null; + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + URL url = classLoader.getResource(classPathResource); + try { + if (URLUtil.isJarURL(url)) { + jarFile = URLUtil.getJarFile(url); + Enumeration enumeration = jarFile.entries(); + String jarEntryName; + while (enumeration.hasMoreElements()) { + jarEntryName = enumeration.nextElement().getName(); + if (jarEntryName.startsWith(classPathResource) && !jarEntryName.endsWith(StrUtil.SLASH)) { + inputStream = classLoader.getResource(jarEntryName).openConnection().getInputStream(); + tmpFile = FileUtil.file(CodeGenerator.TMP_DIR + jarEntryName); + FileUtil.writeFromStream(inputStream, tmpFile); + } + } + } + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + IoUtil.close(inputStream); + IoUtil.close(jarFile); + } + } } diff --git a/src/main/java/com/github/mengweijin/generator/mojo/MybatisPlusGeneratorMojo.java b/src/main/java/com/github/mengweijin/generator/mojo/MybatisPlusGeneratorMojo.java index cdb5ae2..d6f4b9d 100644 --- a/src/main/java/com/github/mengweijin/generator/mojo/MybatisPlusGeneratorMojo.java +++ b/src/main/java/com/github/mengweijin/generator/mojo/MybatisPlusGeneratorMojo.java @@ -21,7 +21,9 @@ public class MybatisPlusGeneratorMojo extends AbstractGeneratorMojo { public void execute() throws MojoExecutionException, MojoFailureException { try { CodeGenerator codeGenerator = this.getCodeGenerator(); - codeGenerator.getParameters().setTemplateLocation(Template.MYBATIS_PLUS.getPath()); + + String templateLocation = CodeGenerator.TMP_DIR + Template.MYBATIS_PLUS.getPath(); + codeGenerator.getParameters().setTemplateLocation(templateLocation); codeGenerator.getParameters().setSuperDaoClass(BaseMapper); codeGenerator.getParameters().setSuperServiceClass(IService); codeGenerator.getParameters().setSuperServiceImplClass(ServiceImpl); @@ -31,4 +33,5 @@ public class MybatisPlusGeneratorMojo extends AbstractGeneratorMojo { throw new RuntimeException(e); } } + } diff --git a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java index a78106d..0f58651 100644 --- a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java +++ b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java @@ -2,18 +2,14 @@ package com.github.mengweijin.generator.util; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; -import cn.hutool.core.util.URLUtil; import com.baomidou.mybatisplus.generator.config.FileOutConfig; import com.github.mengweijin.generator.CodeGenerator; import com.github.mengweijin.generator.Parameters; import com.github.mengweijin.generator.config.CustomerFileOutConfig; + import java.io.File; -import java.net.URL; import java.util.ArrayList; -import java.util.Enumeration; import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; /** * @author mengweijin @@ -23,58 +19,22 @@ public class FileOutConfigUtils { public static List loadTemplatesToGetFileOutConfig(CodeGenerator codeGenerator) { Parameters parameters = codeGenerator.getParameters(); // 自定义输出配置 - List fileOutConfigList = null; - URL url = Thread.currentThread().getContextClassLoader().getResource(parameters.getTemplateLocation()); - if (URLUtil.isFileURL(url)) { - fileOutConfigList = FileOutConfigUtils.resolveByFileSystem(codeGenerator); - } else if (URLUtil.isJarURL(url)) { - JarFile jarFile = URLUtil.getJarFile(url); - fileOutConfigList = FileOutConfigUtils.resolveByJarFile(codeGenerator, jarFile); - } - return fileOutConfigList; - } + List fileOutConfigList = new ArrayList<>();; - private static List resolveByFileSystem(CodeGenerator codeGenerator) { - List fileOutConfigList = new ArrayList<>(); - Parameters parameters = codeGenerator.getParameters(); - - List fileList = FileUtil.loopFiles(parameters.getTemplateLocation(), + List templateFileList = FileUtil.loopFiles(parameters.getTemplateLocation(), file -> file.isFile() && file.getName().toLowerCase().endsWith(parameters.getTemplateType().name())); - if (CollectionUtil.isEmpty(fileList)) { + if (CollectionUtil.isEmpty(templateFileList)) { throw new RuntimeException("No template files found in location " + parameters.getTemplateLocation()); + } else { + String message = "Found " + templateFileList.size() + "template files in location " + parameters.getTemplateLocation(); + System.out.println(message); } - String message = "Found " + fileList.size() + "template files in location " + parameters.getTemplateLocation(); - System.out.println(message); - - fileList.forEach(file -> { - // 自定义配置会被优先输出 - String templatePath = codeGenerator.getBaseDir().getAbsolutePath() + File.separator + parameters.getTemplateLocation() + file.getName(); - FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, templatePath); + templateFileList.forEach(file -> { + FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, file.getAbsolutePath()); fileOutConfigList.add(fileOutConfig); }); - - return fileOutConfigList; - } - - // TODO 在MOJO入口处,对jar包里面的模板文件先做拷贝到文件系统,然后统一使用文件系统绝对路径。就可以删除这个方法了 - private static List resolveByJarFile(CodeGenerator codeGenerator, JarFile jarFile) { - Parameters parameters = codeGenerator.getParameters(); - List fileOutConfigList = new ArrayList<>(); - - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - Enumeration enumeration = jarFile.entries(); - String jarEntryName; - while (enumeration.hasMoreElements()) { - jarEntryName = enumeration.nextElement().getName(); - if (jarEntryName.startsWith(parameters.getTemplateLocation()) && !jarEntryName.endsWith("/")) { - String templatePath = FileUtil.readString(classLoader.getResource(jarEntryName), "UTF-8"); - FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, templatePath); - fileOutConfigList.add(fileOutConfig); - } - } - return fileOutConfigList; } } -- Gitee From 69c2550abb171aa87ffe2bbc2822c5652c1a84fd Mon Sep 17 00:00:00 2001 From: mengweijin <1002284406@qq.com> Date: Wed, 23 Dec 2020 22:28:57 +0800 Subject: [PATCH 4/7] update --- .../mengweijin/generator/Parameters.java | 5 +- .../config/DefaultDataSourceConfig.java | 23 ++++++-- .../generator/config/DefaultGlobalConfig.java | 11 ++-- .../config/DefaultPackageConfig.java | 1 - .../CustomerAbstractTemplateEngine.java | 54 ------------------- .../factory/TemplateEngineFactory.java | 5 +- 6 files changed, 27 insertions(+), 72 deletions(-) delete mode 100644 src/main/java/com/github/mengweijin/generator/engine/CustomerAbstractTemplateEngine.java diff --git a/src/main/java/com/github/mengweijin/generator/Parameters.java b/src/main/java/com/github/mengweijin/generator/Parameters.java index a539061..63a5f3d 100644 --- a/src/main/java/com/github/mengweijin/generator/Parameters.java +++ b/src/main/java/com/github/mengweijin/generator/Parameters.java @@ -9,10 +9,7 @@ import lombok.Data; @Data public class Parameters { - /** - * Absolute path - */ - private String outputDir; + private String outputPackage; private String author; diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java index 50406ea..a272213 100644 --- a/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java @@ -3,6 +3,7 @@ package com.github.mengweijin.generator.config; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.file.FileNameUtil; +import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; @@ -10,11 +11,13 @@ import com.github.mengweijin.generator.CodeGenerator; import com.github.mengweijin.generator.DbInfo; import com.github.mengweijin.generator.reader.BootFileReaderFactory; import org.apache.maven.model.Resource; + import java.io.File; +import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; -import java.sql.SQLException; import java.util.List; +import java.util.Properties; /** * @author mengweijin @@ -105,8 +108,22 @@ public class DefaultDataSourceConfig extends DataSourceConfig { Connection conn; try { Class.forName(this.getDriverName(), true, Thread.currentThread().getContextClassLoader()); - conn = DriverManager.getConnection(this.getUrl(), this.getUsername(), this.getPassword()); - } catch (ClassNotFoundException | SQLException e) { + + Properties info = new Properties(); + if (this.getUsername() != null) { + info.put("user", this.getUsername()); + } + if (this.getPassword() != null) { + info.put("password", this.getPassword()); + } + + Method method = ReflectUtil.getMethod( + DriverManager.class, + "getConnection", + String.class, Properties.class, Class.class); + method.setAccessible(true); + conn = ReflectUtil.invokeStatic(method, this.getUrl(), info, null); + } catch (Exception e) { throw new RuntimeException(e); } return conn; diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java index 2f0ff75..a761f26 100644 --- a/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java @@ -1,7 +1,6 @@ package com.github.mengweijin.generator.config; import cn.hutool.core.io.FileUtil; -import cn.hutool.core.util.StrUtil; import cn.hutool.system.SystemUtil; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.github.mengweijin.generator.CodeGenerator; @@ -31,13 +30,9 @@ public class DefaultGlobalConfig extends GlobalConfig { this.setAuthor(Optional.ofNullable(parameters.getAuthor()).orElse(SystemUtil.getUserInfo().getName())); - if(StrUtil.isBlank(parameters.getOutputDir())) { - File output = FileUtil.file(baseDir, "target/code-generator/"); - this.setOutputDir(output.getAbsolutePath()); - } else { - this.setOutputDir(parameters.getOutputDir()); - } - + File output = FileUtil.file(baseDir, "target/code-generator/"); + this.setOutputDir(output.getAbsolutePath()); + this.setFileOverride(true); this.setOpen(false); } } diff --git a/src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java index 05ba0d2..0e89a1d 100644 --- a/src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java @@ -19,7 +19,6 @@ public class DefaultPackageConfig extends PackageConfig { * Initialize the default parameter. */ public void init() { - //String moduleName = StrUtil.subAfter(parameter.getOutputDir(), StrUtil.SLASH, true); this.setParent("com.github.mengweijin"); this.setModuleName(null); this.setEntity(null); diff --git a/src/main/java/com/github/mengweijin/generator/engine/CustomerAbstractTemplateEngine.java b/src/main/java/com/github/mengweijin/generator/engine/CustomerAbstractTemplateEngine.java deleted file mode 100644 index de40359..0000000 --- a/src/main/java/com/github/mengweijin/generator/engine/CustomerAbstractTemplateEngine.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.github.mengweijin.generator.engine; - -import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; -import com.baomidou.mybatisplus.generator.InjectionConfig; -import com.baomidou.mybatisplus.generator.config.FileOutConfig; -import com.baomidou.mybatisplus.generator.config.TemplateConfig; -import com.baomidou.mybatisplus.generator.config.po.TableInfo; -import com.baomidou.mybatisplus.generator.config.rules.FileType; -import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine; - -import java.util.List; -import java.util.Map; - -/** - * @author mengweijin - */ -public abstract class CustomerAbstractTemplateEngine extends AbstractTemplateEngine { - - @Override - public AbstractTemplateEngine batchOutput() { - try { - List tableInfoList = getConfigBuilder().getTableInfoList(); - for (TableInfo tableInfo : tableInfoList) { - Map objectMap = getObjectMap(tableInfo); - Map pathInfo = getConfigBuilder().getPathInfo(); - TemplateConfig template = getConfigBuilder().getTemplate(); - // 自定义内容 - InjectionConfig injectionConfig = getConfigBuilder().getInjectionConfig(); - if (null != injectionConfig) { - injectionConfig.initTableMap(tableInfo); - objectMap.put("cfg", injectionConfig.getMap()); - List focList = injectionConfig.getFileOutConfigList(); - if (CollectionUtils.isNotEmpty(focList)) { - String output; - for (FileOutConfig foc : focList) { - output = foc.outputFile(tableInfo); - if (isCreate(FileType.OTHER, output)) { - writer(objectMap, foc.getTemplatePath(), output); - } else { - System.out.println("Warning: File already exists when generated! " + output); - } - } - } else { - - } - } - } - } catch (Exception e) { - System.err.println("Exception: Can't create file, please check the configuration! " + e.toString()); - logger.error("Can't create file, please check the configuration!", e); - } - return this; - } -} diff --git a/src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java b/src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java index 34e5450..3a97824 100644 --- a/src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java +++ b/src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java @@ -1,10 +1,11 @@ package com.github.mengweijin.generator.factory; 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.github.mengweijin.generator.engine.BeetlStringTemplateEngine; import com.github.mengweijin.generator.enums.TemplateType; + import java.util.HashMap; /** @@ -15,7 +16,7 @@ public class TemplateEngineFactory { public static final HashMap map = new HashMap<>(3); static { - map.put(TemplateType.beetl, new BeetlTemplateEngine()); + map.put(TemplateType.beetl, new BeetlStringTemplateEngine()); map.put(TemplateType.freemarker, new FreemarkerTemplateEngine()); map.put(TemplateType.velocity, new VelocityTemplateEngine()); } -- Gitee From 39d30b21832dd77ebbadabe81a49c51e2e3ead48 Mon Sep 17 00:00:00 2001 From: mengweijin <1002284406@qq.com> Date: Wed, 23 Dec 2020 22:29:08 +0800 Subject: [PATCH 5/7] update --- .../engine/BeetlStringTemplateEngine.java | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java b/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java index 0c7d61d..95cb536 100644 --- a/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java +++ b/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java @@ -1,11 +1,14 @@ package com.github.mengweijin.generator.engine; +import cn.hutool.core.io.FileUtil; import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder; import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine; +import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine; import org.beetl.core.Configuration; import org.beetl.core.GroupTemplate; import org.beetl.core.Template; import org.beetl.core.resource.StringTemplateResourceLoader; + import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; @@ -13,7 +16,7 @@ import java.util.Map; /** * @author mengweijin */ -public class BeetlStringTemplateEngine extends CustomerAbstractTemplateEngine { +public class BeetlStringTemplateEngine extends BeetlTemplateEngine { private GroupTemplate groupTemplate; @@ -22,29 +25,23 @@ public class BeetlStringTemplateEngine extends CustomerAbstractTemplateEngine { super.init(configBuilder); try { Configuration cfg = Configuration.defaultConfiguration(); - StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader(); - groupTemplate = new GroupTemplate(resourceLoader, cfg); + groupTemplate = new GroupTemplate(new StringTemplateResourceLoader(), cfg); } catch (IOException e) { logger.error(e.getMessage(), e); } return this; } - /** - * - * @param objectMap - * @param templateString template String - * @param outputFile - * @throws Exception - */ @Override - public void writer(Map objectMap, String templateString, String outputFile) throws Exception { - Template template = groupTemplate.getTemplate(templateString); + public void writer(Map objectMap, String templatePath, String outputFile) throws Exception { + // read template content from template path + String templateContent = FileUtil.readUtf8String(templatePath); + Template template = groupTemplate.getTemplate(templateContent); try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) { template.binding(objectMap); template.renderTo(fileOutputStream); } - logger.debug("文件:" + outputFile); + logger.debug("模板:" + templatePath + "; 文件:" + outputFile); } @Override -- Gitee From 472d680b6c5b8cabbb8bb7ab4aae3c5d829a5ed8 Mon Sep 17 00:00:00 2001 From: mengweijin <1002284406@qq.com> Date: Wed, 23 Dec 2020 23:14:08 +0800 Subject: [PATCH 6/7] update --- pom.xml | 12 ++ .../engine/BeetlStringTemplateEngine.java | 11 +- .../generator/util/FileOutConfigUtils.java | 2 +- .../mybatis-plus/controller.java.btl | 111 +++---------- .../mybatis-plus/controller.java.ftl | 39 +++++ .../templates/mybatis-plus/controller.java.vm | 41 +++++ .../templates/mybatis-plus/entity.java.btl | 135 ++++++++++++--- .../templates/mybatis-plus/entity.java.ftl | 152 +++++++++++++++++ .../templates/mybatis-plus/entity.java.vm | 155 ++++++++++++++++++ .../templates/mybatis-plus/entity.kt.btl | 124 ++++++++++++++ .../templates/mybatis-plus/entity.kt.ftl | 115 +++++++++++++ .../templates/mybatis-plus/entity.kt.vm | 114 +++++++++++++ .../templates/mybatis-plus/mapper.java.btl | 20 +-- .../templates/mybatis-plus/mapper.java.ftl | 20 +++ .../templates/mybatis-plus/mapper.java.vm | 20 +++ .../templates/mybatis-plus/mapper.xml.btl | 38 ++++- .../templates/mybatis-plus/mapper.xml.ftl | 39 +++++ .../templates/mybatis-plus/mapper.xml.vm | 39 +++++ .../mybatis-plus/service.impl.java.btl | 24 --- .../templates/mybatis-plus/service.java.btl | 10 +- .../templates/mybatis-plus/service.java.ftl | 20 +++ .../templates/mybatis-plus/service.java.vm | 20 +++ .../mybatis-plus/serviceImpl.java.btl | 26 +++ .../mybatis-plus/serviceImpl.java.ftl | 26 +++ .../mybatis-plus/serviceImpl.java.vm | 26 +++ 25 files changed, 1188 insertions(+), 151 deletions(-) create mode 100644 src/main/resources/templates/mybatis-plus/controller.java.ftl create mode 100644 src/main/resources/templates/mybatis-plus/controller.java.vm create mode 100644 src/main/resources/templates/mybatis-plus/entity.java.ftl create mode 100644 src/main/resources/templates/mybatis-plus/entity.java.vm create mode 100644 src/main/resources/templates/mybatis-plus/entity.kt.btl create mode 100644 src/main/resources/templates/mybatis-plus/entity.kt.ftl create mode 100644 src/main/resources/templates/mybatis-plus/entity.kt.vm create mode 100644 src/main/resources/templates/mybatis-plus/mapper.java.ftl create mode 100644 src/main/resources/templates/mybatis-plus/mapper.java.vm create mode 100644 src/main/resources/templates/mybatis-plus/mapper.xml.ftl create mode 100644 src/main/resources/templates/mybatis-plus/mapper.xml.vm delete mode 100644 src/main/resources/templates/mybatis-plus/service.impl.java.btl create mode 100644 src/main/resources/templates/mybatis-plus/service.java.ftl create mode 100644 src/main/resources/templates/mybatis-plus/service.java.vm create mode 100644 src/main/resources/templates/mybatis-plus/serviceImpl.java.btl create mode 100644 src/main/resources/templates/mybatis-plus/serviceImpl.java.ftl create mode 100644 src/main/resources/templates/mybatis-plus/serviceImpl.java.vm diff --git a/pom.xml b/pom.xml index 98d41e5..0fe5374 100644 --- a/pom.xml +++ b/pom.xml @@ -58,6 +58,18 @@ beetl ${beetl.version} + + + org.apache.tomcat.embed + tomcat-embed-core + 9.0.39 + org.apache.velocity velocity-engine-core diff --git a/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java b/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java index 95cb536..1768639 100644 --- a/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java +++ b/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java @@ -3,7 +3,6 @@ package com.github.mengweijin.generator.engine; import cn.hutool.core.io.FileUtil; import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder; import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine; -import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine; import org.beetl.core.Configuration; import org.beetl.core.GroupTemplate; import org.beetl.core.Template; @@ -16,7 +15,7 @@ import java.util.Map; /** * @author mengweijin */ -public class BeetlStringTemplateEngine extends BeetlTemplateEngine { +public class BeetlStringTemplateEngine extends AbstractTemplateEngine { private GroupTemplate groupTemplate; @@ -27,7 +26,8 @@ public class BeetlStringTemplateEngine extends BeetlTemplateEngine { Configuration cfg = Configuration.defaultConfiguration(); groupTemplate = new GroupTemplate(new StringTemplateResourceLoader(), cfg); } catch (IOException e) { - logger.error(e.getMessage(), e); + e.printStackTrace(); + throw new RuntimeException(e); } return this; } @@ -40,8 +40,11 @@ public class BeetlStringTemplateEngine extends BeetlTemplateEngine { try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) { template.binding(objectMap); template.renderTo(fileOutputStream); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); } - logger.debug("模板:" + templatePath + "; 文件:" + outputFile); + System.out.println("模板:" + templatePath + "; 文件:" + outputFile); } @Override diff --git a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java index 0f58651..200488f 100644 --- a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java +++ b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java @@ -27,7 +27,7 @@ public class FileOutConfigUtils { if (CollectionUtil.isEmpty(templateFileList)) { throw new RuntimeException("No template files found in location " + parameters.getTemplateLocation()); } else { - String message = "Found " + templateFileList.size() + "template files in location " + parameters.getTemplateLocation(); + String message = "Found " + templateFileList.size() + " template files in location " + parameters.getTemplateLocation(); System.out.println(message); } diff --git a/src/main/resources/templates/mybatis-plus/controller.java.btl b/src/main/resources/templates/mybatis-plus/controller.java.btl index 0e473fb..92b5afa 100644 --- a/src/main/resources/templates/mybatis-plus/controller.java.btl +++ b/src/main/resources/templates/mybatis-plus/controller.java.btl @@ -1,104 +1,39 @@ -package ${basePackage}.controller; +package ${package.Controller}; + -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; + +<% if(restControllerStyle){ %> import org.springframework.web.bind.annotation.RestController; -import javax.validation.Valid; -import org.hibernate.validator.constraints.Range; -import ${basePackage}.service.${entityName}Service; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.baomidou.mybatisplus.core.metadata.IPage; +<% }else{ %> +import org.springframework.stereotype.Controller; +<% } %> <% if(isNotEmpty(superControllerClassPackage)){ %> import ${superControllerClassPackage}; <% } %> -import ${basePackage}.entity.${entityName}; /** *

- * ${entityName} Controller + * ${table.comment!} 前端控制器 *

* * @author ${author} - * @date ${date} + * @since ${date} */ -@Slf4j -@Validated +<% if(restControllerStyle){ %> @RestController -@RequestMapping("<% if(isNotEmpty(moduleName)){ %>/${moduleName}<% } %>/${entityVariableName}") -public class ${entityName}Controller <% if(isNotEmpty(superControllerName)){ %>extends ${superControllerName}<% } %> { - - /** - *

- * ${entityName}Service - *

- */ - @Autowired - private ${entityName}Service ${entityVariableName}Service; - - /** - *

- * Get ${entityName} by id - *

- * @param id id - * @return ${entityName} - */ - @GetMapping("/{id}") - public ${entityName} getById(@Valid @Range @PathVariable("id") Long id) { - return ${entityVariableName}Service.getById(id); - } - - /** - *

- * Get ${entityName} page list by ${entityName} - *

- * @param page page - * @param ${entityVariableName} ${entityVariableName} - * @return IPage<${entityName}> - */ - @GetMapping - public IPage<${entityName}> getPage(IPage<${entityName}> page, @Valid ${entityName} ${entityVariableName}) { - return ${entityVariableName}Service.page(page, new QueryWrapper<>(${entityVariableName})); - } - - /** - *

- * Add ${entityName} - *

- * @param ${entityVariableName} ${entityVariableName} - */ - @PostMapping - public void add(@Valid @RequestBody ${entityName} ${entityVariableName}) { - ${entityVariableName}Service.save(${entityVariableName}); - } - - /** - *

- * Update ${entityName} - *

- * @param ${entityVariableName} ${entityVariableName} - */ - @PutMapping - public void update(@Valid @RequestBody ${entityName} ${entityVariableName}) { - ${entityVariableName}Service.updateById(${entityVariableName}); - } - - /** - *

- * Delete ${entityName} by id - *

- * @param id id - */ - @DeleteMapping("/{id}") - public void delete(@Valid @Range @PathVariable("id") Long id) { - ${entityVariableName}Service.removeById(id); - } +<% }else{ %> +@Controller +<% } %> +@RequestMapping("<% if(isNotEmpty(package.ModuleName)){ %>/${package.ModuleName}<% } %>/<% if(isNotEmpty(controllerMappingHyphenStyle)){ %>${controllerMappingHyphen}<% }else{ %>${table.entityPath}<% } %>") +<% if(kotlin){ %> +class ${table.controllerName}<% if(isNotEmpty(superControllerClass)){ %> : ${superControllerClass}()<% } %> +<% }else{ %> + <% if(isNotEmpty(superControllerClass)){ %> +public class ${table.controllerName} extends ${superControllerClass} { + <% }else{ %> +public class ${table.controllerName} { + <% } %> } +<% } %> diff --git a/src/main/resources/templates/mybatis-plus/controller.java.ftl b/src/main/resources/templates/mybatis-plus/controller.java.ftl new file mode 100644 index 0000000..69a9f81 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/controller.java.ftl @@ -0,0 +1,39 @@ +package ${package.Controller}; + + +import org.springframework.web.bind.annotation.RequestMapping; + +<#if restControllerStyle> +import org.springframework.web.bind.annotation.RestController; +<#else> +import org.springframework.stereotype.Controller; + +<#if superControllerClassPackage??> +import ${superControllerClassPackage}; + + +/** + *

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

+ * + * @author ${author} + * @since ${date} + */ +<#if restControllerStyle> +@RestController +<#else> +@Controller + +@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") +<#if kotlin> +class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}() +<#else> +<#if superControllerClass??> +public class ${table.controllerName} extends ${superControllerClass} { +<#else> +public class ${table.controllerName} { + + +} + diff --git a/src/main/resources/templates/mybatis-plus/controller.java.vm b/src/main/resources/templates/mybatis-plus/controller.java.vm new file mode 100644 index 0000000..bbe5936 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/controller.java.vm @@ -0,0 +1,41 @@ +package ${package.Controller}; + + +import org.springframework.web.bind.annotation.RequestMapping; + +#if(${restControllerStyle}) +import org.springframework.web.bind.annotation.RestController; +#else +import org.springframework.stereotype.Controller; +#end +#if(${superControllerClassPackage}) +import ${superControllerClassPackage}; +#end + +/** + *

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

+ * + * @author ${author} + * @since ${date} + */ +#if(${restControllerStyle}) +@RestController +#else +@Controller +#end +@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") +#if(${kotlin}) +class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end + +#else +#if(${superControllerClass}) +public class ${table.controllerName} extends ${superControllerClass} { +#else +public class ${table.controllerName} { +#end + +} + +#end \ No newline at end of file diff --git a/src/main/resources/templates/mybatis-plus/entity.java.btl b/src/main/resources/templates/mybatis-plus/entity.java.btl index 8bedf1a..a9616c4 100644 --- a/src/main/resources/templates/mybatis-plus/entity.java.btl +++ b/src/main/resources/templates/mybatis-plus/entity.java.btl @@ -1,67 +1,162 @@ -package ${basePackage}.entity; - -import com.baomidou.mybatisplus.annotation.TableField; -<% if(isNotEmpty(superEntityClassPackage)){ %> -import ${superEntityClassPackage}; -<% }else{ %> -import java.io.Serializable; +package ${package.Entity}; +<% for(pkg in table.importPackages){ %> +import ${pkg}; <% } %> +<% if(swagger2){ %> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +<% } %> +<% if(entityLombokModel){ %> import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; -<% for(pkg in fieldImportPackages){ %> -import ${pkg}; <% } %> - /** *

* ${table.comment!} *

* * @author ${author} - * @date ${date} + * @since ${date} */ +<% if(entityLombokModel){ %> @Data -@Accessors(chain = true) -<% if(isNotEmpty(superEntityName)){ %> + <% if(isNotEmpty(superEntityClass)){ %> @EqualsAndHashCode(callSuper = true) -<% }else{ %> + <% }else{ %> @EqualsAndHashCode(callSuper = false) + <% } %> +@Accessors(chain = true) +<% } %> +<% if(table.convert){ %> +@TableName("${table.name}") <% } %> -<% if(isNotEmpty(superEntityName)){ %> -public class ${entityName} extends ${superEntityName} { +<% if(swagger2){ %> +@ApiModel(value="${entity}对象", description="${table.comment!''}") +<% } %> +<% if(isNotEmpty(superEntityClass)){ %> +public class ${entity} extends ${superEntityClass}<% if(activeRecord){ %><${entity}><%}%>{ +<% }else if(activeRecord){ %> +public class ${entity} extends Model<${entity}> { <% }else{ %> -public class ${entityName} implements Serializable { +public class ${entity} implements Serializable { <% } %> +<% if(entitySerialVersionUID){ %> private static final long serialVersionUID = 1L; +<% } %> <% /** -----------BEGIN 字段循环遍历----------- **/ %> <% for(field in table.fields){ %> + <% + if(field.keyFlag){ + var keyPropertyName = field.propertyName; + } + %> <% if(isNotEmpty(field.comment)){ %> + <% if(swagger2){ %> + @ApiModelProperty(value = "${field.comment}") + <% }else{ %> /** - * ${field.comment!} + * ${field.comment} */ + <% } %> <% } %> <% if(field.keyFlag){ %> + <% + /*主键*/ + %> <% if(field.keyIdentityFlag){ %> @TableId(value = "${field.name}", type = IdType.AUTO) <% }else if(isNotEmpty(idType)){ %> @TableId(value = "${field.name}", type = IdType.${idType}) <% }else if(field.convert){ %> @TableId("${field.name}") - <% } %> + <% } %> + <% + /*普通字段*/ + %> <% }else if(isNotEmpty(field.fill)){ %> <% if(field.convert){ %> @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) <% }else{ %> @TableField(fill = FieldFill.${field.fill}) <% } %> - <% }else{ %> + <% }else if(field.convert){ %> @TableField("${field.name}") <% } %> + <% + /*乐观锁注解*/ + %> + <% if(versionFieldName!'' == field.name){ %> + @Version + <% } %> + <% + /*逻辑删除注解*/ + %> + <% if(logicDeleteFieldName!'' == field.name){ %> + @TableLogic + <% } %> private ${field.propertyType} ${field.propertyName}; <% } %> <% /** -----------END 字段循环遍历----------- **/ %> +<% if(!entityLombokModel){ %> + <% for(field in table.fields){ %> + <% + var getprefix =''; + if(field.propertyType=='boolean'){ + getprefix='is'; + }else{ + getprefix='get'; + } + %> + public ${field.propertyType} ${getprefix}${field.capitalName}() { + return ${field.propertyName}; + } + + <% if(entityBuilderModel){ %> + public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + <% }else{ %> + public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + <% } %> + this.${field.propertyName} = ${field.propertyName}; + <% if(entityBuilderModel){ %> + return this; + <% } %> + } + + <% } %> +<% } %> +<% if(entityColumnConstant){ %> + <% for(field in table.fields){ %> + public static final String ${strutil.toUpperCase(field.name)} = "${field.name}"; + + <% } %> +<% } %> +<% if(activeRecord){ %> + @Override + protected Serializable pkVal() { + <% if(isNotEmpty(keyPropertyName)){ %> + return this.${keyPropertyName}; + <% }else{ %> + return null; + <% } %> + } + +<% } %> +<% if(!entityLombokModel){ %> + @Override + public String toString() { + return "${entity}{" + + <% for(field in table.fields){ %> + <% if(fieldLP.index==0){ %> + "${field.propertyName}=" + ${field.propertyName} + + <% }else{ %> + ", ${field.propertyName}=" + ${field.propertyName} + + <% } %> + <% } %> + "}"; + } +<% } %> } diff --git a/src/main/resources/templates/mybatis-plus/entity.java.ftl b/src/main/resources/templates/mybatis-plus/entity.java.ftl new file mode 100644 index 0000000..c698d36 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/entity.java.ftl @@ -0,0 +1,152 @@ +package ${package.Entity}; + +<#list table.importPackages as pkg> +import ${pkg}; + +<#if swagger2> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +<#if entityLombokModel> +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + + +/** + *

+ * ${table.comment!} + *

+ * + * @author ${author} + * @since ${date} + */ +<#if entityLombokModel> +@Data + <#if superEntityClass??> +@EqualsAndHashCode(callSuper = true) + <#else> +@EqualsAndHashCode(callSuper = false) + +@Accessors(chain = true) + +<#if table.convert> +@TableName("${table.name}") + +<#if swagger2> +@ApiModel(value="${entity}对象", description="${table.comment!}") + +<#if superEntityClass??> +public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { +<#elseif activeRecord> +public class ${entity} extends Model<${entity}> { +<#else> +public class ${entity} implements Serializable { + + +<#if entitySerialVersionUID> + private static final long serialVersionUID = 1L; + +<#-- ---------- BEGIN 字段循环遍历 ----------> +<#list table.fields as field> + <#if field.keyFlag> + <#assign keyPropertyName="${field.propertyName}"/> + + + <#if field.comment!?length gt 0> + <#if swagger2> + @ApiModelProperty(value = "${field.comment}") + <#else> + /** + * ${field.comment} + */ + + + <#if field.keyFlag> + <#-- 主键 --> + <#if field.keyIdentityFlag> + @TableId(value = "${field.name}", type = IdType.AUTO) + <#elseif idType??> + @TableId(value = "${field.name}", type = IdType.${idType}) + <#elseif field.convert> + @TableId("${field.name}") + + <#-- 普通字段 --> + <#elseif field.fill??> + <#-- ----- 存在字段填充设置 -----> + <#if field.convert> + @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) + <#else> + @TableField(fill = FieldFill.${field.fill}) + + <#elseif field.convert> + @TableField("${field.name}") + + <#-- 乐观锁注解 --> + <#if (versionFieldName!"") == field.name> + @Version + + <#-- 逻辑删除注解 --> + <#if (logicDeleteFieldName!"") == field.name> + @TableLogic + + private ${field.propertyType} ${field.propertyName}; + +<#------------ END 字段循环遍历 ----------> + +<#if !entityLombokModel> + <#list table.fields as field> + <#if field.propertyType == "boolean"> + <#assign getprefix="is"/> + <#else> + <#assign getprefix="get"/> + + public ${field.propertyType} ${getprefix}${field.capitalName}() { + return ${field.propertyName}; + } + + <#if entityBuilderModel> + public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + <#else> + public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + + this.${field.propertyName} = ${field.propertyName}; + <#if entityBuilderModel> + return this; + + } + + + +<#if entityColumnConstant> + <#list table.fields as field> + public static final String ${field.name?upper_case} = "${field.name}"; + + + +<#if activeRecord> + @Override + protected Serializable pkVal() { + <#if keyPropertyName??> + return this.${keyPropertyName}; + <#else> + return null; + + } + + +<#if !entityLombokModel> + @Override + public String toString() { + return "${entity}{" + + <#list table.fields as field> + <#if field_index==0> + "${field.propertyName}=" + ${field.propertyName} + + <#else> + ", ${field.propertyName}=" + ${field.propertyName} + + + + "}"; + } + +} diff --git a/src/main/resources/templates/mybatis-plus/entity.java.vm b/src/main/resources/templates/mybatis-plus/entity.java.vm new file mode 100644 index 0000000..3aa95f5 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/entity.java.vm @@ -0,0 +1,155 @@ +package ${package.Entity}; + +#foreach($pkg in ${table.importPackages}) +import ${pkg}; +#end +#if(${swagger2}) +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +#end +#if(${entityLombokModel}) +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; +#end + +/** + *

+ * $!{table.comment} + *

+ * + * @author ${author} + * @since ${date} + */ +#if(${entityLombokModel}) +@Data + #if(${superEntityClass}) +@EqualsAndHashCode(callSuper = true) + #else +@EqualsAndHashCode(callSuper = false) + #end +@Accessors(chain = true) +#end +#if(${table.convert}) +@TableName("${table.name}") +#end +#if(${swagger2}) +@ApiModel(value="${entity}对象", description="$!{table.comment}") +#end +#if(${superEntityClass}) +public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end { +#elseif(${activeRecord}) +public class ${entity} extends Model<${entity}> { +#else +public class ${entity} implements Serializable { +#end + +#if(${entitySerialVersionUID}) + private static final long serialVersionUID=1L; +#end +## ---------- BEGIN 字段循环遍历 ---------- +#foreach($field in ${table.fields}) + +#if(${field.keyFlag}) +#set($keyPropertyName=${field.propertyName}) +#end +#if("$!field.comment" != "") + #if(${swagger2}) + @ApiModelProperty(value = "${field.comment}") + #else + /** + * ${field.comment} + */ + #end +#end +#if(${field.keyFlag}) +## 主键 + #if(${field.keyIdentityFlag}) + @TableId(value = "${field.name}", type = IdType.AUTO) + #elseif(!$null.isNull(${idType}) && "$!idType" != "") + @TableId(value = "${field.name}", type = IdType.${idType}) + #elseif(${field.convert}) + @TableId("${field.name}") + #end +## 普通字段 +#elseif(${field.fill}) +## ----- 存在字段填充设置 ----- + #if(${field.convert}) + @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) + #else + @TableField(fill = FieldFill.${field.fill}) + #end +#elseif(${field.convert}) + @TableField("${field.name}") +#end +## 乐观锁注解 +#if(${versionFieldName}==${field.name}) + @Version +#end +## 逻辑删除注解 +#if(${logicDeleteFieldName}==${field.name}) + @TableLogic +#end + private ${field.propertyType} ${field.propertyName}; +#end +## ---------- END 字段循环遍历 ---------- + +#if(!${entityLombokModel}) +#foreach($field in ${table.fields}) + #if(${field.propertyType.equals("boolean")}) + #set($getprefix="is") + #else + #set($getprefix="get") + #end + + public ${field.propertyType} ${getprefix}${field.capitalName}() { + return ${field.propertyName}; + } + + #if(${entityBuilderModel}) + public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + #else + public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { + #end + this.${field.propertyName} = ${field.propertyName}; + #if(${entityBuilderModel}) + return this; + #end + } +#end +## --foreach end--- +#end +## --end of #if(!${entityLombokModel})-- + +#if(${entityColumnConstant}) + #foreach($field in ${table.fields}) + public static final String ${field.name.toUpperCase()} = "${field.name}"; + + #end +#end +#if(${activeRecord}) + @Override + protected Serializable pkVal() { + #if(${keyPropertyName}) + return this.${keyPropertyName}; + #else + return null; + #end + } + +#end +#if(!${entityLombokModel}) + @Override + public String toString() { + return "${entity}{" + + #foreach($field in ${table.fields}) + #if($!{foreach.index}==0) + "${field.propertyName}=" + ${field.propertyName} + + #else + ", ${field.propertyName}=" + ${field.propertyName} + + #end + #end + "}"; + } +#end +} diff --git a/src/main/resources/templates/mybatis-plus/entity.kt.btl b/src/main/resources/templates/mybatis-plus/entity.kt.btl new file mode 100644 index 0000000..5b6f3e9 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/entity.kt.btl @@ -0,0 +1,124 @@ +package ${package.Entity} +<% for(pkg in table.importPackages){ %> +import ${pkg} +<% } %> +<% if(swagger2){ %> +import io.swagger.annotations.ApiModel +import io.swagger.annotations.ApiModelProperty +<% } %> +/** + *

+ * ${table.comment!} + *

+ * + * @author ${author} + * @since ${date} + */ +<% if(table.convert){ %> +@TableName("${table.name}") +<% } %> +<% if(swagger2){ %> +@ApiModel(value="${entity}对象", description="${table.comment!''}") +<% } %> +<% if(isNotEmpty(superEntityClass)){ %> +class ${entity} : ${superEntityClass}<% if(activeRecord){ %><${entity}><%}%>{ +<% }else if(activeRecord){ %> +class ${entity} : Model<${entity}> { +<% }else{ %> +class ${entity} : Serializable { +<% } %> + +<% /** -----------BEGIN 字段循环遍历----------- **/ %> +<% for(field in table.fields){ %> + <% + if(field.keyFlag){ + var keyPropertyName = field.propertyName; + } + %> + + <% if(isNotEmpty(field.comment)){ %> + <% if(swagger2){ %> + @ApiModelProperty(value = "${field.comment}") + <% }else{ %> + /** + * ${field.comment} + */ + <% } %> + <% } %> + <% if(field.keyFlag){ %> + <% + /*主键*/ + %> + <% if(field.keyIdentityFlag){ %> + @TableId(value = "${field.name}", type = IdType.AUTO) + <% }else if(isNotEmpty(idType)){ %> + @TableId(value = "${field.name}", type = IdType.${idType}) + <% }else if(field.convert){ %> + @TableId("${field.name}") + <% } %> + <% + /*普通字段*/ + %> + <% }else if(isNotEmpty(field.fill)){ %> + <% if(field.convert){ %> + @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) + <% }else{ %> + @TableField(fill = FieldFill.${field.fill}) + <% } %> + <% }else if(field.convert){ %> + @TableField("${field.name}") + <% } %> + <% + /*乐观锁注解*/ + %> + <% if(versionFieldName!'' == field.name){ %> + @Version + <% } %> + <% + /*逻辑删除注解*/ + %> + <% if(logicDeleteFieldName!'' == field.name){ %> + @TableLogic + <% } %> + <% if(field.propertyType == 'Integer'){ %> + var ${field.propertyName}: Int ? = null + <% }else{ %> + var ${field.propertyName}: ${field.propertyType} ? = null + <% } %> +<% } %> +<% /** -----------END 字段循环遍历----------- **/ %> + +<% if(entityColumnConstant){ %> + companion object { + <% for(field in table.fields){ %> + const val ${strutil.toUpperCase(field.name)} : String = "${field.name}" + <% } %> + } +<% } %> +<% if(activeRecord){ %> + @Override + override fun pkVal(): Serializable? { + <% if(isNotEmpty(keyPropertyName)){ %> + return this.${keyPropertyName} + <% }else{ %> + return null; + <% } %> + } + +<% } %> + +<% if(!entityLombokModel){ %> + @Override + override fun toString(): String { + return "${entity}{" + + <% for(field in table.fields){ %> + <% if(fieldLP.index==0){ %> + "${field.propertyName}=" + ${field.propertyName} + + <% }else{ %> + ", ${field.propertyName}=" + ${field.propertyName} + + <% } %> + <% } %> + "}" + } +<% } %> +} diff --git a/src/main/resources/templates/mybatis-plus/entity.kt.ftl b/src/main/resources/templates/mybatis-plus/entity.kt.ftl new file mode 100644 index 0000000..178715a --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/entity.kt.ftl @@ -0,0 +1,115 @@ +package ${package.Entity} + +<#list table.importPackages as pkg> +import ${pkg} + +<#if swagger2> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + *

+ * ${table.comment} + *

+ * + * @author ${author} + * @since ${date} + */ +<#if table.convert> +@TableName("${table.name}") + +<#if swagger2> +@ApiModel(value="${entity}对象", description="${table.comment!}") + +<#if superEntityClass??> +class ${entity} : ${superEntityClass}<#if activeRecord><${entity}> { +<#elseif activeRecord> +class ${entity} : Model<${entity}>() { +<#else> +class ${entity} : Serializable { + + +<#-- ---------- BEGIN 字段循环遍历 ----------> +<#list table.fields as field> +<#if field.keyFlag> + <#assign keyPropertyName="${field.propertyName}"/> + + +<#if field.comment!?length gt 0> +<#if swagger2> + @ApiModelProperty(value = "${field.comment}") +<#else> + /** + * ${field.comment} + */ + + +<#if field.keyFlag> +<#-- 主键 --> +<#if field.keyIdentityFlag> + @TableId(value = "${field.name}", type = IdType.AUTO) +<#elseif idType ??> + @TableId(value = "${field.name}", type = IdType.${idType}) +<#elseif field.convert> + @TableId("${field.name}") + +<#-- 普通字段 --> +<#elseif field.fill??> +<#-- ----- 存在字段填充设置 -----> +<#if field.convert> + @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) +<#else> + @TableField(fill = FieldFill.${field.fill}) + +<#elseif field.convert> + @TableField("${field.name}") + +<#-- 乐观锁注解 --> +<#if (versionFieldName!"") == field.name> + @Version + +<#-- 逻辑删除注解 --> +<#if (logicDeleteFieldName!"") == field.name> + @TableLogic + + <#if field.propertyType == "Integer"> + var ${field.propertyName}: Int? = null + <#else> + var ${field.propertyName}: ${field.propertyType}? = null + + +<#-- ---------- END 字段循环遍历 ----------> + + +<#if entityColumnConstant> + companion object { +<#list table.fields as field> + + const val ${field.name?upper_case} : String = "${field.name}" + + + } + + +<#if activeRecord> + override fun pkVal(): Serializable? { +<#if keyPropertyName??> + return ${keyPropertyName} +<#else> + return null + + } + + + override fun toString(): String { + return "${entity}{" + +<#list table.fields as field> +<#if field_index==0> + "${field.propertyName}=" + ${field.propertyName} + +<#else> + ", ${field.propertyName}=" + ${field.propertyName} + + + + "}" + } +} diff --git a/src/main/resources/templates/mybatis-plus/entity.kt.vm b/src/main/resources/templates/mybatis-plus/entity.kt.vm new file mode 100644 index 0000000..adcef6a --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/entity.kt.vm @@ -0,0 +1,114 @@ +package ${package.Entity}; + +#foreach($pkg in ${table.importPackages}) +import ${pkg}; +#end +#if(${swagger2}) +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +#end +/** + *

+ * $!{table.comment} + *

+ * + * @author ${author} + * @since ${date} + */ +#if(${table.convert}) +@TableName("${table.name}") +#end +#if(${swagger2}) +@ApiModel(value="${entity}对象", description="$!{table.comment}") +#end +#if(${superEntityClass}) +class ${entity} : ${superEntityClass}#if(${activeRecord})<${entity}>#end() { +#elseif(${activeRecord}) +class ${entity} : Model<${entity}>() { +#else +class ${entity} : Serializable { +#end + +## ---------- BEGIN 字段循环遍历 ---------- +#foreach($field in ${table.fields}) +#if(${field.keyFlag}) +#set($keyPropertyName=${field.propertyName}) +#end +#if("$!field.comment" != "") + #if(${swagger2}) + @ApiModelProperty(value = "${field.comment}") + #else + /** + * ${field.comment} + */ + #end +#end +#if(${field.keyFlag}) +## 主键 +#if(${field.keyIdentityFlag}) + @TableId(value = "${field.name}", type = IdType.AUTO) +#elseif(!$null.isNull(${idType}) && "$!idType" != "") + @TableId(value = "${field.name}", type = IdType.${idType}) +#elseif(${field.convert}) + @TableId("${field.name}") +#end +## 普通字段 +#elseif(${field.fill}) +## ----- 存在字段填充设置 ----- +#if(${field.convert}) + @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) +#else + @TableField(fill = FieldFill.${field.fill}) +#end +#elseif(${field.convert}) + @TableField("${field.name}") +#end +## 乐观锁注解 +#if(${versionFieldName}==${field.name}) + @Version +#end +## 逻辑删除注解 +#if(${logicDeleteFieldName}==${field.name}) + @TableLogic +#end + #if(${field.propertyType} == "Integer") + var ${field.propertyName}: Int? = null + #else + var ${field.propertyName}: ${field.propertyType}? = null + #end +#end +## ---------- END 字段循环遍历 ---------- + + +#if(${entityColumnConstant}) + companion object { +#foreach($field in ${table.fields}) + + const val ${field.name.toUpperCase()} : String = "${field.name}" + +#end + } + +#end +#if(${activeRecord}) + override fun pkVal(): Serializable? { +#if(${keyPropertyName}) + return ${keyPropertyName} +#else + return null +#end + } + +#end + override fun toString(): String { + return "${entity}{" + +#foreach($field in ${table.fields}) +#if($!{foreach.index}==0) + "${field.propertyName}=" + ${field.propertyName} + +#else + ", ${field.propertyName}=" + ${field.propertyName} + +#end +#end + "}" + } +} diff --git a/src/main/resources/templates/mybatis-plus/mapper.java.btl b/src/main/resources/templates/mybatis-plus/mapper.java.btl index 345ac3d..95bf7ad 100644 --- a/src/main/resources/templates/mybatis-plus/mapper.java.btl +++ b/src/main/resources/templates/mybatis-plus/mapper.java.btl @@ -1,20 +1,20 @@ -package ${basePackage}.mapper; +package ${package.Mapper}; -import ${basePackage}.entity.${entityName}; -<% if(isNotEmpty(superDaoClassPackage)){ %> -import ${superDaoClassPackage}; -<% } %> -import org.apache.ibatis.annotations.Mapper; +import ${package.Entity}.${entity}; +import ${superMapperClassPackage}; /** *

- * ${table.comment!} Mapper + * ${table.comment!} Mapper 接口 *

* * @author ${author} - * @date ${date} + * @since ${date} */ -@Mapper -public interface ${entityName}Mapper <% if(isNotEmpty(superDaoName)){ %>extends ${superDaoName}<${entityName}><% } %> { +<% if(kotlin){ %> +interface ${table.mapperName} : ${superMapperClass}<${entity}> +<% }else{ %> +public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { } +<% } %> diff --git a/src/main/resources/templates/mybatis-plus/mapper.java.ftl b/src/main/resources/templates/mybatis-plus/mapper.java.ftl new file mode 100644 index 0000000..53da4ae --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/mapper.java.ftl @@ -0,0 +1,20 @@ +package ${package.Mapper}; + +import ${package.Entity}.${entity}; +import ${superMapperClassPackage}; + +/** + *

+ * ${table.comment!} Mapper 接口 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if kotlin> +interface ${table.mapperName} : ${superMapperClass}<${entity}> +<#else> +public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { + +} + diff --git a/src/main/resources/templates/mybatis-plus/mapper.java.vm b/src/main/resources/templates/mybatis-plus/mapper.java.vm new file mode 100644 index 0000000..3a6f3a5 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/mapper.java.vm @@ -0,0 +1,20 @@ +package ${package.Mapper}; + +import ${package.Entity}.${entity}; +import ${superMapperClassPackage}; + +/** + *

+ * $!{table.comment} Mapper 接口 + *

+ * + * @author ${author} + * @since ${date} + */ +#if(${kotlin}) +interface ${table.mapperName} : ${superMapperClass}<${entity}> +#else +public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { + +} +#end diff --git a/src/main/resources/templates/mybatis-plus/mapper.xml.btl b/src/main/resources/templates/mybatis-plus/mapper.xml.btl index 20cc5a3..4de8945 100644 --- a/src/main/resources/templates/mybatis-plus/mapper.xml.btl +++ b/src/main/resources/templates/mybatis-plus/mapper.xml.btl @@ -1,5 +1,41 @@ - + +<% if(enableCache){ %> + + + +<% } %> +<% if(baseResultMap){ %> + + +<% for(field in table.fields){ %> + <% /** 生成主键排在第一位 **/ %> + <% if(field.keyFlag){ %> + + <% } %> +<% } %> +<% for(field in table.commonFields){ %> + <% /** 生成公共字段 **/ %> + +<% } %> +<% for(field in table.fields){ %> + <% /** 生成普通字段 **/ %> + <% if(!field.keyFlag){ %> + + <% } %> +<% } %> + +<% } %> +<% if(baseColumnList){ %> + + +<% for(field in table.commonFields){ %> + ${field.name}, +<% } %> + ${table.fieldNames} + + +<% } %> diff --git a/src/main/resources/templates/mybatis-plus/mapper.xml.ftl b/src/main/resources/templates/mybatis-plus/mapper.xml.ftl new file mode 100644 index 0000000..d9ca71c --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/mapper.xml.ftl @@ -0,0 +1,39 @@ + + + + +<#if enableCache> + + + + +<#if baseResultMap> + + +<#list table.fields as field> +<#if field.keyFlag><#--生成主键排在第一位--> + + + +<#list table.commonFields as field><#--生成公共字段 --> + + +<#list table.fields as field> +<#if !field.keyFlag><#--生成普通字段 --> + + + + + + +<#if baseColumnList> + + +<#list table.commonFields as field> + ${field.name}, + + ${table.fieldNames} + + + + diff --git a/src/main/resources/templates/mybatis-plus/mapper.xml.vm b/src/main/resources/templates/mybatis-plus/mapper.xml.vm new file mode 100644 index 0000000..3af28b0 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/mapper.xml.vm @@ -0,0 +1,39 @@ + + + + +#if(${enableCache}) + + + +#end +#if(${baseResultMap}) + + +#foreach($field in ${table.fields}) +#if(${field.keyFlag})##生成主键排在第一位 + +#end +#end +#foreach($field in ${table.commonFields})##生成公共字段 + +#end +#foreach($field in ${table.fields}) +#if(!${field.keyFlag})##生成普通字段 + +#end +#end + + +#end +#if(${baseColumnList}) + + +#foreach($field in ${table.commonFields}) + ${field.name}, +#end + ${table.fieldNames} + + +#end + diff --git a/src/main/resources/templates/mybatis-plus/service.impl.java.btl b/src/main/resources/templates/mybatis-plus/service.impl.java.btl deleted file mode 100644 index d624bdb..0000000 --- a/src/main/resources/templates/mybatis-plus/service.impl.java.btl +++ /dev/null @@ -1,24 +0,0 @@ -package ${basePackage}.service.impl; - -import ${basePackage}.entity.${entityName}; -import ${basePackage}.mapper.${entityName}Mapper; -import ${basePackage}.service.${entityName}Service; -<% if(isNotEmpty(superServiceImplClassPackage)){ %> -import ${superServiceImplClassPackage}; -<% } %> -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -/** - *

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

- * - * @author ${author} - * @since ${date} - */ -@Service -@Transactional(rollbackFor = Exception.class) -public class ${entityName}ServiceImpl <% if(isNotEmpty(superServiceImplName)){ %>extends ${superServiceImplName}<${entityName}Mapper, ${entityName}><% } %> implements ${entityName}Service { - -} diff --git a/src/main/resources/templates/mybatis-plus/service.java.btl b/src/main/resources/templates/mybatis-plus/service.java.btl index 1342661..c3f6388 100644 --- a/src/main/resources/templates/mybatis-plus/service.java.btl +++ b/src/main/resources/templates/mybatis-plus/service.java.btl @@ -1,6 +1,6 @@ -package ${basePackage}.service; +package ${package.Service}; -import ${basePackage}.entity.${entityName}; +import ${package.Entity}.${entity}; import ${superServiceClassPackage}; /** @@ -11,6 +11,10 @@ import ${superServiceClassPackage}; * @author ${author} * @since ${date} */ -public interface ${entityName}Service <% if(isNotEmpty(superServiceName)){ %>extends ${superServiceName}<${entityName}><% } %> { +<% if(kotlin){ %> +interface ${table.serviceName} : ${superServiceClass}<${entity}> +<% }else{ %> +public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { } +<% } %> diff --git a/src/main/resources/templates/mybatis-plus/service.java.ftl b/src/main/resources/templates/mybatis-plus/service.java.ftl new file mode 100644 index 0000000..e3232f3 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/service.java.ftl @@ -0,0 +1,20 @@ +package ${package.Service}; + +import ${package.Entity}.${entity}; +import ${superServiceClassPackage}; + +/** + *

+ * ${table.comment!} 服务类 + *

+ * + * @author ${author} + * @since ${date} + */ +<#if kotlin> +interface ${table.serviceName} : ${superServiceClass}<${entity}> +<#else> +public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { + +} + diff --git a/src/main/resources/templates/mybatis-plus/service.java.vm b/src/main/resources/templates/mybatis-plus/service.java.vm new file mode 100644 index 0000000..e6f7828 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/service.java.vm @@ -0,0 +1,20 @@ +package ${package.Service}; + +import ${package.Entity}.${entity}; +import ${superServiceClassPackage}; + +/** + *

+ * $!{table.comment} 服务类 + *

+ * + * @author ${author} + * @since ${date} + */ +#if(${kotlin}) +interface ${table.serviceName} : ${superServiceClass}<${entity}> +#else +public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { + +} +#end diff --git a/src/main/resources/templates/mybatis-plus/serviceImpl.java.btl b/src/main/resources/templates/mybatis-plus/serviceImpl.java.btl new file mode 100644 index 0000000..9a62911 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/serviceImpl.java.btl @@ -0,0 +1,26 @@ +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 +<% if(kotlin){ %> +open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { + +} +<% }else{ %> +public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { + +} +<% } %> diff --git a/src/main/resources/templates/mybatis-plus/serviceImpl.java.ftl b/src/main/resources/templates/mybatis-plus/serviceImpl.java.ftl new file mode 100644 index 0000000..aeebd14 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/serviceImpl.java.ftl @@ -0,0 +1,26 @@ +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 +<#if kotlin> +open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { + +} +<#else> +public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { + +} + diff --git a/src/main/resources/templates/mybatis-plus/serviceImpl.java.vm b/src/main/resources/templates/mybatis-plus/serviceImpl.java.vm new file mode 100644 index 0000000..a5ed504 --- /dev/null +++ b/src/main/resources/templates/mybatis-plus/serviceImpl.java.vm @@ -0,0 +1,26 @@ +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 +#if(${kotlin}) +open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { + +} +#else +public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { + +} +#end -- Gitee From 51ed62c85e581976728843e72a79dceded509c32 Mon Sep 17 00:00:00 2001 From: mengweijin <1002284406@qq.com> Date: Wed, 23 Dec 2020 23:17:31 +0800 Subject: [PATCH 7/7] update --- .../mybatis-plus/controller.java.ftl | 39 ----- .../templates/mybatis-plus/controller.java.vm | 41 ----- .../templates/mybatis-plus/entity.java.ftl | 152 ----------------- .../templates/mybatis-plus/entity.java.vm | 155 ------------------ .../templates/mybatis-plus/entity.kt.ftl | 115 ------------- .../templates/mybatis-plus/entity.kt.vm | 114 ------------- .../templates/mybatis-plus/mapper.java.ftl | 20 --- .../templates/mybatis-plus/mapper.java.vm | 20 --- .../templates/mybatis-plus/mapper.xml.ftl | 39 ----- .../templates/mybatis-plus/mapper.xml.vm | 39 ----- ...iceImpl.java.btl => service.impl.java.btl} | 0 .../templates/mybatis-plus/service.java.ftl | 20 --- .../templates/mybatis-plus/service.java.vm | 20 --- .../mybatis-plus/serviceImpl.java.ftl | 26 --- .../mybatis-plus/serviceImpl.java.vm | 26 --- 15 files changed, 826 deletions(-) delete mode 100644 src/main/resources/templates/mybatis-plus/controller.java.ftl delete mode 100644 src/main/resources/templates/mybatis-plus/controller.java.vm delete mode 100644 src/main/resources/templates/mybatis-plus/entity.java.ftl delete mode 100644 src/main/resources/templates/mybatis-plus/entity.java.vm delete mode 100644 src/main/resources/templates/mybatis-plus/entity.kt.ftl delete mode 100644 src/main/resources/templates/mybatis-plus/entity.kt.vm delete mode 100644 src/main/resources/templates/mybatis-plus/mapper.java.ftl delete mode 100644 src/main/resources/templates/mybatis-plus/mapper.java.vm delete mode 100644 src/main/resources/templates/mybatis-plus/mapper.xml.ftl delete mode 100644 src/main/resources/templates/mybatis-plus/mapper.xml.vm rename src/main/resources/templates/mybatis-plus/{serviceImpl.java.btl => service.impl.java.btl} (100%) delete mode 100644 src/main/resources/templates/mybatis-plus/service.java.ftl delete mode 100644 src/main/resources/templates/mybatis-plus/service.java.vm delete mode 100644 src/main/resources/templates/mybatis-plus/serviceImpl.java.ftl delete mode 100644 src/main/resources/templates/mybatis-plus/serviceImpl.java.vm diff --git a/src/main/resources/templates/mybatis-plus/controller.java.ftl b/src/main/resources/templates/mybatis-plus/controller.java.ftl deleted file mode 100644 index 69a9f81..0000000 --- a/src/main/resources/templates/mybatis-plus/controller.java.ftl +++ /dev/null @@ -1,39 +0,0 @@ -package ${package.Controller}; - - -import org.springframework.web.bind.annotation.RequestMapping; - -<#if restControllerStyle> -import org.springframework.web.bind.annotation.RestController; -<#else> -import org.springframework.stereotype.Controller; - -<#if superControllerClassPackage??> -import ${superControllerClassPackage}; - - -/** - *

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

- * - * @author ${author} - * @since ${date} - */ -<#if restControllerStyle> -@RestController -<#else> -@Controller - -@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}") -<#if kotlin> -class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}() -<#else> -<#if superControllerClass??> -public class ${table.controllerName} extends ${superControllerClass} { -<#else> -public class ${table.controllerName} { - - -} - diff --git a/src/main/resources/templates/mybatis-plus/controller.java.vm b/src/main/resources/templates/mybatis-plus/controller.java.vm deleted file mode 100644 index bbe5936..0000000 --- a/src/main/resources/templates/mybatis-plus/controller.java.vm +++ /dev/null @@ -1,41 +0,0 @@ -package ${package.Controller}; - - -import org.springframework.web.bind.annotation.RequestMapping; - -#if(${restControllerStyle}) -import org.springframework.web.bind.annotation.RestController; -#else -import org.springframework.stereotype.Controller; -#end -#if(${superControllerClassPackage}) -import ${superControllerClassPackage}; -#end - -/** - *

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

- * - * @author ${author} - * @since ${date} - */ -#if(${restControllerStyle}) -@RestController -#else -@Controller -#end -@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") -#if(${kotlin}) -class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end - -#else -#if(${superControllerClass}) -public class ${table.controllerName} extends ${superControllerClass} { -#else -public class ${table.controllerName} { -#end - -} - -#end \ No newline at end of file diff --git a/src/main/resources/templates/mybatis-plus/entity.java.ftl b/src/main/resources/templates/mybatis-plus/entity.java.ftl deleted file mode 100644 index c698d36..0000000 --- a/src/main/resources/templates/mybatis-plus/entity.java.ftl +++ /dev/null @@ -1,152 +0,0 @@ -package ${package.Entity}; - -<#list table.importPackages as pkg> -import ${pkg}; - -<#if swagger2> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -<#if entityLombokModel> -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; - - -/** - *

- * ${table.comment!} - *

- * - * @author ${author} - * @since ${date} - */ -<#if entityLombokModel> -@Data - <#if superEntityClass??> -@EqualsAndHashCode(callSuper = true) - <#else> -@EqualsAndHashCode(callSuper = false) - -@Accessors(chain = true) - -<#if table.convert> -@TableName("${table.name}") - -<#if swagger2> -@ApiModel(value="${entity}对象", description="${table.comment!}") - -<#if superEntityClass??> -public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}> { -<#elseif activeRecord> -public class ${entity} extends Model<${entity}> { -<#else> -public class ${entity} implements Serializable { - - -<#if entitySerialVersionUID> - private static final long serialVersionUID = 1L; - -<#-- ---------- BEGIN 字段循环遍历 ----------> -<#list table.fields as field> - <#if field.keyFlag> - <#assign keyPropertyName="${field.propertyName}"/> - - - <#if field.comment!?length gt 0> - <#if swagger2> - @ApiModelProperty(value = "${field.comment}") - <#else> - /** - * ${field.comment} - */ - - - <#if field.keyFlag> - <#-- 主键 --> - <#if field.keyIdentityFlag> - @TableId(value = "${field.name}", type = IdType.AUTO) - <#elseif idType??> - @TableId(value = "${field.name}", type = IdType.${idType}) - <#elseif field.convert> - @TableId("${field.name}") - - <#-- 普通字段 --> - <#elseif field.fill??> - <#-- ----- 存在字段填充设置 -----> - <#if field.convert> - @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) - <#else> - @TableField(fill = FieldFill.${field.fill}) - - <#elseif field.convert> - @TableField("${field.name}") - - <#-- 乐观锁注解 --> - <#if (versionFieldName!"") == field.name> - @Version - - <#-- 逻辑删除注解 --> - <#if (logicDeleteFieldName!"") == field.name> - @TableLogic - - private ${field.propertyType} ${field.propertyName}; - -<#------------ END 字段循环遍历 ----------> - -<#if !entityLombokModel> - <#list table.fields as field> - <#if field.propertyType == "boolean"> - <#assign getprefix="is"/> - <#else> - <#assign getprefix="get"/> - - public ${field.propertyType} ${getprefix}${field.capitalName}() { - return ${field.propertyName}; - } - - <#if entityBuilderModel> - public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { - <#else> - public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { - - this.${field.propertyName} = ${field.propertyName}; - <#if entityBuilderModel> - return this; - - } - - - -<#if entityColumnConstant> - <#list table.fields as field> - public static final String ${field.name?upper_case} = "${field.name}"; - - - -<#if activeRecord> - @Override - protected Serializable pkVal() { - <#if keyPropertyName??> - return this.${keyPropertyName}; - <#else> - return null; - - } - - -<#if !entityLombokModel> - @Override - public String toString() { - return "${entity}{" + - <#list table.fields as field> - <#if field_index==0> - "${field.propertyName}=" + ${field.propertyName} + - <#else> - ", ${field.propertyName}=" + ${field.propertyName} + - - - "}"; - } - -} diff --git a/src/main/resources/templates/mybatis-plus/entity.java.vm b/src/main/resources/templates/mybatis-plus/entity.java.vm deleted file mode 100644 index 3aa95f5..0000000 --- a/src/main/resources/templates/mybatis-plus/entity.java.vm +++ /dev/null @@ -1,155 +0,0 @@ -package ${package.Entity}; - -#foreach($pkg in ${table.importPackages}) -import ${pkg}; -#end -#if(${swagger2}) -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -#end -#if(${entityLombokModel}) -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.experimental.Accessors; -#end - -/** - *

- * $!{table.comment} - *

- * - * @author ${author} - * @since ${date} - */ -#if(${entityLombokModel}) -@Data - #if(${superEntityClass}) -@EqualsAndHashCode(callSuper = true) - #else -@EqualsAndHashCode(callSuper = false) - #end -@Accessors(chain = true) -#end -#if(${table.convert}) -@TableName("${table.name}") -#end -#if(${swagger2}) -@ApiModel(value="${entity}对象", description="$!{table.comment}") -#end -#if(${superEntityClass}) -public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end { -#elseif(${activeRecord}) -public class ${entity} extends Model<${entity}> { -#else -public class ${entity} implements Serializable { -#end - -#if(${entitySerialVersionUID}) - private static final long serialVersionUID=1L; -#end -## ---------- BEGIN 字段循环遍历 ---------- -#foreach($field in ${table.fields}) - -#if(${field.keyFlag}) -#set($keyPropertyName=${field.propertyName}) -#end -#if("$!field.comment" != "") - #if(${swagger2}) - @ApiModelProperty(value = "${field.comment}") - #else - /** - * ${field.comment} - */ - #end -#end -#if(${field.keyFlag}) -## 主键 - #if(${field.keyIdentityFlag}) - @TableId(value = "${field.name}", type = IdType.AUTO) - #elseif(!$null.isNull(${idType}) && "$!idType" != "") - @TableId(value = "${field.name}", type = IdType.${idType}) - #elseif(${field.convert}) - @TableId("${field.name}") - #end -## 普通字段 -#elseif(${field.fill}) -## ----- 存在字段填充设置 ----- - #if(${field.convert}) - @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) - #else - @TableField(fill = FieldFill.${field.fill}) - #end -#elseif(${field.convert}) - @TableField("${field.name}") -#end -## 乐观锁注解 -#if(${versionFieldName}==${field.name}) - @Version -#end -## 逻辑删除注解 -#if(${logicDeleteFieldName}==${field.name}) - @TableLogic -#end - private ${field.propertyType} ${field.propertyName}; -#end -## ---------- END 字段循环遍历 ---------- - -#if(!${entityLombokModel}) -#foreach($field in ${table.fields}) - #if(${field.propertyType.equals("boolean")}) - #set($getprefix="is") - #else - #set($getprefix="get") - #end - - public ${field.propertyType} ${getprefix}${field.capitalName}() { - return ${field.propertyName}; - } - - #if(${entityBuilderModel}) - public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) { - #else - public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) { - #end - this.${field.propertyName} = ${field.propertyName}; - #if(${entityBuilderModel}) - return this; - #end - } -#end -## --foreach end--- -#end -## --end of #if(!${entityLombokModel})-- - -#if(${entityColumnConstant}) - #foreach($field in ${table.fields}) - public static final String ${field.name.toUpperCase()} = "${field.name}"; - - #end -#end -#if(${activeRecord}) - @Override - protected Serializable pkVal() { - #if(${keyPropertyName}) - return this.${keyPropertyName}; - #else - return null; - #end - } - -#end -#if(!${entityLombokModel}) - @Override - public String toString() { - return "${entity}{" + - #foreach($field in ${table.fields}) - #if($!{foreach.index}==0) - "${field.propertyName}=" + ${field.propertyName} + - #else - ", ${field.propertyName}=" + ${field.propertyName} + - #end - #end - "}"; - } -#end -} diff --git a/src/main/resources/templates/mybatis-plus/entity.kt.ftl b/src/main/resources/templates/mybatis-plus/entity.kt.ftl deleted file mode 100644 index 178715a..0000000 --- a/src/main/resources/templates/mybatis-plus/entity.kt.ftl +++ /dev/null @@ -1,115 +0,0 @@ -package ${package.Entity} - -<#list table.importPackages as pkg> -import ${pkg} - -<#if swagger2> -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - *

- * ${table.comment} - *

- * - * @author ${author} - * @since ${date} - */ -<#if table.convert> -@TableName("${table.name}") - -<#if swagger2> -@ApiModel(value="${entity}对象", description="${table.comment!}") - -<#if superEntityClass??> -class ${entity} : ${superEntityClass}<#if activeRecord><${entity}> { -<#elseif activeRecord> -class ${entity} : Model<${entity}>() { -<#else> -class ${entity} : Serializable { - - -<#-- ---------- BEGIN 字段循环遍历 ----------> -<#list table.fields as field> -<#if field.keyFlag> - <#assign keyPropertyName="${field.propertyName}"/> - - -<#if field.comment!?length gt 0> -<#if swagger2> - @ApiModelProperty(value = "${field.comment}") -<#else> - /** - * ${field.comment} - */ - - -<#if field.keyFlag> -<#-- 主键 --> -<#if field.keyIdentityFlag> - @TableId(value = "${field.name}", type = IdType.AUTO) -<#elseif idType ??> - @TableId(value = "${field.name}", type = IdType.${idType}) -<#elseif field.convert> - @TableId("${field.name}") - -<#-- 普通字段 --> -<#elseif field.fill??> -<#-- ----- 存在字段填充设置 -----> -<#if field.convert> - @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) -<#else> - @TableField(fill = FieldFill.${field.fill}) - -<#elseif field.convert> - @TableField("${field.name}") - -<#-- 乐观锁注解 --> -<#if (versionFieldName!"") == field.name> - @Version - -<#-- 逻辑删除注解 --> -<#if (logicDeleteFieldName!"") == field.name> - @TableLogic - - <#if field.propertyType == "Integer"> - var ${field.propertyName}: Int? = null - <#else> - var ${field.propertyName}: ${field.propertyType}? = null - - -<#-- ---------- END 字段循环遍历 ----------> - - -<#if entityColumnConstant> - companion object { -<#list table.fields as field> - - const val ${field.name?upper_case} : String = "${field.name}" - - - } - - -<#if activeRecord> - override fun pkVal(): Serializable? { -<#if keyPropertyName??> - return ${keyPropertyName} -<#else> - return null - - } - - - override fun toString(): String { - return "${entity}{" + -<#list table.fields as field> -<#if field_index==0> - "${field.propertyName}=" + ${field.propertyName} + -<#else> - ", ${field.propertyName}=" + ${field.propertyName} + - - - "}" - } -} diff --git a/src/main/resources/templates/mybatis-plus/entity.kt.vm b/src/main/resources/templates/mybatis-plus/entity.kt.vm deleted file mode 100644 index adcef6a..0000000 --- a/src/main/resources/templates/mybatis-plus/entity.kt.vm +++ /dev/null @@ -1,114 +0,0 @@ -package ${package.Entity}; - -#foreach($pkg in ${table.importPackages}) -import ${pkg}; -#end -#if(${swagger2}) -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -#end -/** - *

- * $!{table.comment} - *

- * - * @author ${author} - * @since ${date} - */ -#if(${table.convert}) -@TableName("${table.name}") -#end -#if(${swagger2}) -@ApiModel(value="${entity}对象", description="$!{table.comment}") -#end -#if(${superEntityClass}) -class ${entity} : ${superEntityClass}#if(${activeRecord})<${entity}>#end() { -#elseif(${activeRecord}) -class ${entity} : Model<${entity}>() { -#else -class ${entity} : Serializable { -#end - -## ---------- BEGIN 字段循环遍历 ---------- -#foreach($field in ${table.fields}) -#if(${field.keyFlag}) -#set($keyPropertyName=${field.propertyName}) -#end -#if("$!field.comment" != "") - #if(${swagger2}) - @ApiModelProperty(value = "${field.comment}") - #else - /** - * ${field.comment} - */ - #end -#end -#if(${field.keyFlag}) -## 主键 -#if(${field.keyIdentityFlag}) - @TableId(value = "${field.name}", type = IdType.AUTO) -#elseif(!$null.isNull(${idType}) && "$!idType" != "") - @TableId(value = "${field.name}", type = IdType.${idType}) -#elseif(${field.convert}) - @TableId("${field.name}") -#end -## 普通字段 -#elseif(${field.fill}) -## ----- 存在字段填充设置 ----- -#if(${field.convert}) - @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) -#else - @TableField(fill = FieldFill.${field.fill}) -#end -#elseif(${field.convert}) - @TableField("${field.name}") -#end -## 乐观锁注解 -#if(${versionFieldName}==${field.name}) - @Version -#end -## 逻辑删除注解 -#if(${logicDeleteFieldName}==${field.name}) - @TableLogic -#end - #if(${field.propertyType} == "Integer") - var ${field.propertyName}: Int? = null - #else - var ${field.propertyName}: ${field.propertyType}? = null - #end -#end -## ---------- END 字段循环遍历 ---------- - - -#if(${entityColumnConstant}) - companion object { -#foreach($field in ${table.fields}) - - const val ${field.name.toUpperCase()} : String = "${field.name}" - -#end - } - -#end -#if(${activeRecord}) - override fun pkVal(): Serializable? { -#if(${keyPropertyName}) - return ${keyPropertyName} -#else - return null -#end - } - -#end - override fun toString(): String { - return "${entity}{" + -#foreach($field in ${table.fields}) -#if($!{foreach.index}==0) - "${field.propertyName}=" + ${field.propertyName} + -#else - ", ${field.propertyName}=" + ${field.propertyName} + -#end -#end - "}" - } -} diff --git a/src/main/resources/templates/mybatis-plus/mapper.java.ftl b/src/main/resources/templates/mybatis-plus/mapper.java.ftl deleted file mode 100644 index 53da4ae..0000000 --- a/src/main/resources/templates/mybatis-plus/mapper.java.ftl +++ /dev/null @@ -1,20 +0,0 @@ -package ${package.Mapper}; - -import ${package.Entity}.${entity}; -import ${superMapperClassPackage}; - -/** - *

- * ${table.comment!} Mapper 接口 - *

- * - * @author ${author} - * @since ${date} - */ -<#if kotlin> -interface ${table.mapperName} : ${superMapperClass}<${entity}> -<#else> -public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { - -} - diff --git a/src/main/resources/templates/mybatis-plus/mapper.java.vm b/src/main/resources/templates/mybatis-plus/mapper.java.vm deleted file mode 100644 index 3a6f3a5..0000000 --- a/src/main/resources/templates/mybatis-plus/mapper.java.vm +++ /dev/null @@ -1,20 +0,0 @@ -package ${package.Mapper}; - -import ${package.Entity}.${entity}; -import ${superMapperClassPackage}; - -/** - *

- * $!{table.comment} Mapper 接口 - *

- * - * @author ${author} - * @since ${date} - */ -#if(${kotlin}) -interface ${table.mapperName} : ${superMapperClass}<${entity}> -#else -public interface ${table.mapperName} extends ${superMapperClass}<${entity}> { - -} -#end diff --git a/src/main/resources/templates/mybatis-plus/mapper.xml.ftl b/src/main/resources/templates/mybatis-plus/mapper.xml.ftl deleted file mode 100644 index d9ca71c..0000000 --- a/src/main/resources/templates/mybatis-plus/mapper.xml.ftl +++ /dev/null @@ -1,39 +0,0 @@ - - - - -<#if enableCache> - - - - -<#if baseResultMap> - - -<#list table.fields as field> -<#if field.keyFlag><#--生成主键排在第一位--> - - - -<#list table.commonFields as field><#--生成公共字段 --> - - -<#list table.fields as field> -<#if !field.keyFlag><#--生成普通字段 --> - - - - - - -<#if baseColumnList> - - -<#list table.commonFields as field> - ${field.name}, - - ${table.fieldNames} - - - - diff --git a/src/main/resources/templates/mybatis-plus/mapper.xml.vm b/src/main/resources/templates/mybatis-plus/mapper.xml.vm deleted file mode 100644 index 3af28b0..0000000 --- a/src/main/resources/templates/mybatis-plus/mapper.xml.vm +++ /dev/null @@ -1,39 +0,0 @@ - - - - -#if(${enableCache}) - - - -#end -#if(${baseResultMap}) - - -#foreach($field in ${table.fields}) -#if(${field.keyFlag})##生成主键排在第一位 - -#end -#end -#foreach($field in ${table.commonFields})##生成公共字段 - -#end -#foreach($field in ${table.fields}) -#if(!${field.keyFlag})##生成普通字段 - -#end -#end - - -#end -#if(${baseColumnList}) - - -#foreach($field in ${table.commonFields}) - ${field.name}, -#end - ${table.fieldNames} - - -#end - diff --git a/src/main/resources/templates/mybatis-plus/serviceImpl.java.btl b/src/main/resources/templates/mybatis-plus/service.impl.java.btl similarity index 100% rename from src/main/resources/templates/mybatis-plus/serviceImpl.java.btl rename to src/main/resources/templates/mybatis-plus/service.impl.java.btl diff --git a/src/main/resources/templates/mybatis-plus/service.java.ftl b/src/main/resources/templates/mybatis-plus/service.java.ftl deleted file mode 100644 index e3232f3..0000000 --- a/src/main/resources/templates/mybatis-plus/service.java.ftl +++ /dev/null @@ -1,20 +0,0 @@ -package ${package.Service}; - -import ${package.Entity}.${entity}; -import ${superServiceClassPackage}; - -/** - *

- * ${table.comment!} 服务类 - *

- * - * @author ${author} - * @since ${date} - */ -<#if kotlin> -interface ${table.serviceName} : ${superServiceClass}<${entity}> -<#else> -public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { - -} - diff --git a/src/main/resources/templates/mybatis-plus/service.java.vm b/src/main/resources/templates/mybatis-plus/service.java.vm deleted file mode 100644 index e6f7828..0000000 --- a/src/main/resources/templates/mybatis-plus/service.java.vm +++ /dev/null @@ -1,20 +0,0 @@ -package ${package.Service}; - -import ${package.Entity}.${entity}; -import ${superServiceClassPackage}; - -/** - *

- * $!{table.comment} 服务类 - *

- * - * @author ${author} - * @since ${date} - */ -#if(${kotlin}) -interface ${table.serviceName} : ${superServiceClass}<${entity}> -#else -public interface ${table.serviceName} extends ${superServiceClass}<${entity}> { - -} -#end diff --git a/src/main/resources/templates/mybatis-plus/serviceImpl.java.ftl b/src/main/resources/templates/mybatis-plus/serviceImpl.java.ftl deleted file mode 100644 index aeebd14..0000000 --- a/src/main/resources/templates/mybatis-plus/serviceImpl.java.ftl +++ /dev/null @@ -1,26 +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 -<#if kotlin> -open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { - -} -<#else> -public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { - -} - diff --git a/src/main/resources/templates/mybatis-plus/serviceImpl.java.vm b/src/main/resources/templates/mybatis-plus/serviceImpl.java.vm deleted file mode 100644 index a5ed504..0000000 --- a/src/main/resources/templates/mybatis-plus/serviceImpl.java.vm +++ /dev/null @@ -1,26 +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 -#if(${kotlin}) -open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} { - -} -#else -public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} { - -} -#end -- Gitee