diff --git a/pom.xml b/pom.xml index 98d41e599dbba2384f0b296a506a387657fd95fa..0fe5374d68419f1456685cb2e826f8425ced3502 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/CodeGenerator.java b/src/main/java/com/github/mengweijin/generator/CodeGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..e7bed75c349f6df9f2288d9584f475d0fb382d61 --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/CodeGenerator.java @@ -0,0 +1,63 @@ +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.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; + +/** + * @author mengweijin + */ +@Data +public class CodeGenerator { + + public static final String TMP_DIR = SystemUtil.get(SystemUtil.TMPDIR) + "code-generator/"; + + private AutoGenerator autoGenerator; + + private Parameters parameters; + + private List resourceList; + + private File baseDir; + + private File sourceDir; + + public void run() { + autoGenerator = new AutoGenerator(); + // 全局配置 + autoGenerator.setGlobalConfig(new DefaultGlobalConfig(this)); + // 数据源配置 + autoGenerator.setDataSource(new DefaultDataSourceConfig(this)); + // 包配置 + autoGenerator.setPackageInfo(new DefaultPackageConfig(this)); + // Mybatis-plus自己的模板配置 + autoGenerator.setTemplate(new DefaultTemplateConfig(this)); + // 自定义配置, 会被优先输出 + InjectionConfig injectionConfig = new DefaultInjectionConfig(this); + injectionConfig.setFileOutConfigList(FileOutConfigUtils.loadTemplatesToGetFileOutConfig(this)); + 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/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 f44bae76039d73d047cea9f81721e435b16d955f..48a3a0b4e41e906e17f63511c598a68d30947111 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 62% rename from src/main/java/com/github/mengweijin/generator/dto/ConfigParameter.java rename to src/main/java/com/github/mengweijin/generator/Parameters.java index 1eaf91dfca795209e3a6905ab2131615ab62b794..63a5f3da4f1e58356987d17e2b04ac26f52fb7a5 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,23 @@ -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 { + + private String outputPackage; 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 +29,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 31ca03352f2eb396cf66f88a90e77a0e27dcedce..0000000000000000000000000000000000000000 --- 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 52% 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 94841e0d667017d89d7ee7e5eeeee1e9f05d0578..6a67f47dcae0a2660de521e0134f2f3734a8db11 100644 --- a/src/main/java/com/github/mengweijin/generator/config/FileOutConfigImpl.java +++ b/src/main/java/com/github/mengweijin/generator/config/CustomerFileOutConfig.java @@ -1,50 +1,52 @@ package com.github.mengweijin.generator.config; +import cn.hutool.core.io.FileUtil; 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.PackageConfig; 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 { - - private final AutoGenerator autoGenerator; +public class CustomerFileOutConfig extends FileOutConfig { - private String templateName; + private final CodeGenerator codeGenerator; /** * - * @param autoGenerator - * @param templateContent E.g.:controller.java.btl 文件中的字符串内容。 + * @param codeGenerator + * @param templatePath 绝对全路径 */ - public FileOutConfigImpl(AutoGenerator autoGenerator, String templateContent, String templateName) { - super(templateContent); - this.autoGenerator = autoGenerator; - this.templateName = templateName; + public CustomerFileOutConfig(CodeGenerator codeGenerator, String templatePath) { + super(templatePath); + this.codeGenerator = codeGenerator; } /** * * @param tableInfo - * @return target/code-generator/controller/SysUserController.java + * @return 全路径名 */ @Override public String outputFile(TableInfo tableInfo) { - StringBuilder outputPath = new StringBuilder(); - String outputDir = autoGenerator.getGlobalConfig().getOutputDir(); - outputPath.append(outputDir); - if(!outputDir.endsWith(StrUtil.SLASH) - && !outputDir.endsWith(StrUtil.BACKSLASH) - && !outputDir.endsWith(StrUtil.DOT)) { + String outputDir = codeGenerator.getAutoGenerator().getGlobalConfig().getOutputDir(); + 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[] packageHierarchy = this.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/dto/DefaultConfigParameter.java b/src/main/java/com/github/mengweijin/generator/config/DefaultDataSourceConfig.java similarity index 44% 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 c5a0a09c5f87f5ff3dea34bd3979a8addb695a91..a2722138903e49ce3a07359229938c64661fddcd 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,28 @@ -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.ReflectUtil; 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.lang.reflect.Method; +import java.sql.Connection; +import java.sql.DriverManager; import java.util.List; -import java.util.Optional; +import java.util.Properties; /** * @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,63 +41,31 @@ 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 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()); - } + private CodeGenerator codeGenerator; - 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); File applicationFile = this.getBootFile(resource, APPLICATION_FILE); if (applicationFile == null) { @@ -135,20 +99,33 @@ 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()); + + 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 new file mode 100644 index 0000000000000000000000000000000000000000..a761f265995e92e594b0a3dfdac2c3cd626d59ef --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultGlobalConfig.java @@ -0,0 +1,38 @@ +package com.github.mengweijin.generator.config; + +import cn.hutool.core.io.FileUtil; +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())); + + 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/DefaultInjectionConfig.java b/src/main/java/com/github/mengweijin/generator/config/DefaultInjectionConfig.java new file mode 100644 index 0000000000000000000000000000000000000000..4a37aa7419817a44cdd701d256b65dfa5775e0fa --- /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 0000000000000000000000000000000000000000..0e89a1def867cea81cc2d9fb36974c399f07cb35 --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/config/DefaultPackageConfig.java @@ -0,0 +1,32 @@ +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() { + 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 0000000000000000000000000000000000000000..d94064b0225769babad0f12c9dfc6625dc559baa --- /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 0000000000000000000000000000000000000000..48f711ffd85e1c55d99124c84f7452f4578785ee --- /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 74a06e59df1ae22a123c44e87e8736a944c2b4c4..0000000000000000000000000000000000000000 --- 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/engine/BeetlStringTemplateEngine.java b/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java index 580d43834b223f3c4e6751bd9ea984dda475454e..17686393765973c6614be78af97a9a4f87f0e6bf 100644 --- a/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java +++ b/src/main/java/com/github/mengweijin/generator/engine/BeetlStringTemplateEngine.java @@ -1,8 +1,8 @@ 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; @@ -15,7 +15,7 @@ import java.util.Map; /** * @author mengweijin */ -public class BeetlStringTemplateEngine extends BeetlTemplateEngine { +public class BeetlStringTemplateEngine extends AbstractTemplateEngine { private GroupTemplate groupTemplate; @@ -24,29 +24,27 @@ public class BeetlStringTemplateEngine extends BeetlTemplateEngine { 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); + e.printStackTrace(); + throw new RuntimeException(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); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); } - logger.debug("文件:" + outputFile); + System.out.println("模板:" + templatePath + "; 文件:" + outputFile); } @Override 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 0000000000000000000000000000000000000000..3a97824abf1a58953cd6a4c121bf3f7d99dc10d8 --- /dev/null +++ b/src/main/java/com/github/mengweijin/generator/factory/TemplateEngineFactory.java @@ -0,0 +1,35 @@ +package com.github.mengweijin.generator.factory; + +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.engine.BeetlStringTemplateEngine; +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 BeetlStringTemplateEngine()); + 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/main/CodeGenerator.java b/src/main/java/com/github/mengweijin/generator/main/CodeGenerator.java deleted file mode 100644 index 513e36925eaee66cb9d393372f4d346ba8bf2932..0000000000000000000000000000000000000000 --- a/src/main/java/com/github/mengweijin/generator/main/CodeGenerator.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.github.mengweijin.generator.main; - -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.util.FileOutConfigUtils; - -import java.util.List; - -/** - * @author mengweijin - */ -public class CodeGenerator { - - /** - * 代码生成器 - */ - private final AutoGenerator autoGenerator = new AutoGenerator(); - - private final DefaultConfigParameter parameter; - - public CodeGenerator(DefaultConfigParameter parameter) { - this.parameter = parameter; - } - - public void run() { - // 全局配置 - autoGenerator.setGlobalConfig(ConfigFactory.getGlobalConfig(parameter)); - // 数据源配置 - autoGenerator.setDataSource(ConfigFactory.getDataSourceConfig(parameter)); - // 包配置 - autoGenerator.setPackageInfo(ConfigFactory.getPackageConfig(parameter)); - // Mybatis-plus自己的模板配置 - autoGenerator.setTemplate(ConfigFactory.getTemplateConfig(parameter)); - - // 自定义配置, 会被优先输出 - InjectionConfig injectionConfig = new InjectionConfigImpl(parameter, autoGenerator); - List fileOutConfigList = FileOutConfigUtils.loadTemplatesToGetFileOutConfig(parameter, autoGenerator); - - // TODO check file exits. - - - injectionConfig.setFileOutConfigList(fileOutConfigList); - autoGenerator.setCfg(injectionConfig); - - // 策略配置 - autoGenerator.setStrategy(ConfigFactory.getStrategyConfig(parameter)); - // 模板引擎 - autoGenerator.setTemplateEngine(ConfigFactory.getTemplateEngine(parameter)); - - autoGenerator.execute(); - } - -} 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 b25a1f55aff913343fe2dfd31141d6f07bf933a1..6484ef41b30028fbe7c0b40c09d3d345f3cb90db 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,12 @@ package com.github.mengweijin.generator.mojo; -import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.io.IoUtil; import cn.hutool.core.lang.JarClassLoader; -import com.github.mengweijin.generator.dto.ConfigParameter; -import com.github.mengweijin.generator.dto.DefaultConfigParameter; +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; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Resource; @@ -12,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 @@ -25,7 +33,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 +59,19 @@ 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.copyTemplateFolderToJavaTmp("templates/"); + 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,10 +100,42 @@ 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); } } + + /** + * + * @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/JpaGeneratorMojo.java b/src/main/java/com/github/mengweijin/generator/mojo/JpaGeneratorMojo.java index 7700a8536ae778421552a53706e51492504d7c9d..4c99d71565db85747ac2d841487a540ca3627444 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 794c3432354fb16b1d1eac8c34b43acdb915f051..d4798c3939d69bfdb60adaa24326cc578a5f81a6 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 e28e17c3381b471f68e3e5ddc08c013b0087e869..d6f4b9df5ef02930fe5e9c24a53c12d23105128c 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,22 +12,26 @@ 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"); + CodeGenerator codeGenerator = this.getCodeGenerator(); - System.out.println("DefaultConfigParameter: " + parameter); - - new CodeGenerator(parameter).run(); + 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); + 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 28681819c8d5074f6052231e08806074e9b79d27..e5c15408a9b7ba3ad594110e2f698f751e9d92b7 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 d24b567f3dab2b0e47525dcf839a2a502311971c..07a29e7fccf8f3154aeea5d2fc618bc912d043a0 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 bb603c73a57b4068d89141f659900640666505a8..c666890734dbaba6308598baf9f2481e64b112de 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 bfe8cdcbcdb6bbaecd0623a10cfd5d01cde74e6b..5757e4f4b30b6d38f7979d0e7e88b2416a055a1e 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 045ade845dbed1cfbb3ecc77f4a952229b7cdc49..200488f799ed7beba1325781d931345c48275325 100644 --- a/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java +++ b/src/main/java/com/github/mengweijin/generator/util/FileOutConfigUtils.java @@ -2,79 +2,39 @@ 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.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.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 */ 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()); - if (URLUtil.isFileURL(url)) { - fileOutConfigList = FileOutConfigUtils.resolveByFileSystem(autoGenerator, parameter); - } else if (URLUtil.isJarURL(url)) { - JarFile jarFile = URLUtil.getJarFile(url); - fileOutConfigList = FileOutConfigUtils.resolveByJarFile(autoGenerator, parameter, jarFile); - } - return fileOutConfigList; - } + List fileOutConfigList = new ArrayList<>();; - private static List resolveByFileSystem(AutoGenerator autoGenerator, DefaultConfigParameter parameter) { - List fileOutConfigList = new ArrayList<>(); + List templateFileList = FileUtil.loopFiles(parameters.getTemplateLocation(), + file -> file.isFile() && file.getName().toLowerCase().endsWith(parameters.getTemplateType().name())); - List fileList = FileUtil.loopFiles(parameter.getTemplateLocation(), - file -> file.isFile() && file.getName().toLowerCase().endsWith(parameter.getTemplateType().name())); - - if (CollectionUtil.isEmpty(fileList)) { - throw new RuntimeException("No template files found in location " + parameter.getTemplateLocation()); + 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 " + parameter.getTemplateLocation(); - System.out.println(message); - - fileList.forEach(file -> { - // 自定义配置会被优先输出 - String templatePath = parameter.getBaseDir().getAbsolutePath() + File.separator + parameter.getTemplateLocation() + file.getName(); - String templateName = file.getName(); - FileOutConfig fileOutConfig = new FileOutConfigImpl(autoGenerator, templatePath, templateName); + templateFileList.forEach(file -> { + FileOutConfig fileOutConfig = new CustomerFileOutConfig(codeGenerator, file.getAbsolutePath()); fileOutConfigList.add(fileOutConfig); }); - - return fileOutConfigList; - } - - private static List resolveByJarFile(AutoGenerator autoGenerator, DefaultConfigParameter parameter, JarFile jarFile) { - 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(parameter.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); - fileOutConfigList.add(fileOutConfig); - } - } - return fileOutConfigList; } } 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 051fb853b776e0b1c84be68b84af644067bc640c..d9607442c4c34512c45bf6b60295e2817512780f 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(); diff --git a/src/main/resources/templates/mybatis-plus/controller.java.btl b/src/main/resources/templates/mybatis-plus/controller.java.btl index 0e473fbd9397e239556170c65992c830b0eb6c1b..92b5afaa11f10abcc30b422d3101298642e203d3 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/entity.java.btl b/src/main/resources/templates/mybatis-plus/entity.java.btl index 8bedf1af0030ff8ed6b92212182e9fac9a442608..a9616c4bc0ebd94d344ccd62f71f4b39fcd9facf 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.kt.btl b/src/main/resources/templates/mybatis-plus/entity.kt.btl new file mode 100644 index 0000000000000000000000000000000000000000..5b6f3e9dc308a6281540f5e9db06cb7bf02fd2b9 --- /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/mapper.java.btl b/src/main/resources/templates/mybatis-plus/mapper.java.btl index 345ac3d72feddffcf65fb94181ba37423e56b50d..95bf7ad918a2a415ec767afeb6e650feaa5e7c26 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.xml.btl b/src/main/resources/templates/mybatis-plus/mapper.xml.btl index 20cc5a3b57bec6ebf1b4be65288e08c9004926cc..4de8945b5a652effbb263cec455150cc477cf145 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/service.impl.java.btl b/src/main/resources/templates/mybatis-plus/service.impl.java.btl index d624bdba517192736b212e1f5ca1d82a1d788332..9a62911a0ca8e6f1cce913c69ffba0c53d2e8b71 100644 --- a/src/main/resources/templates/mybatis-plus/service.impl.java.btl +++ b/src/main/resources/templates/mybatis-plus/service.impl.java.btl @@ -1,13 +1,10 @@ -package ${basePackage}.service.impl; +package ${package.ServiceImpl}; -import ${basePackage}.entity.${entityName}; -import ${basePackage}.mapper.${entityName}Mapper; -import ${basePackage}.service.${entityName}Service; -<% if(isNotEmpty(superServiceImplClassPackage)){ %> +import ${package.Entity}.${entity}; +import ${package.Mapper}.${table.mapperName}; +import ${package.Service}.${table.serviceName}; import ${superServiceImplClassPackage}; -<% } %> import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; /** *

@@ -18,7 +15,12 @@ import org.springframework.transaction.annotation.Transactional; * @since ${date} */ @Service -@Transactional(rollbackFor = Exception.class) -public class ${entityName}ServiceImpl <% if(isNotEmpty(superServiceImplName)){ %>extends ${superServiceImplName}<${entityName}Mapper, ${entityName}><% } %> implements ${entityName}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/service.java.btl b/src/main/resources/templates/mybatis-plus/service.java.btl index 13426613636c76e33a2d60b67789ec23ed2bff23..c3f6388287500afaa2f544fff74b3217c5d3f10e 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}> { } +<% } %>