diff --git a/.gitignore b/.gitignore index f38bb47..ccb76ff 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,6 @@ out *.iml -*.idea \ No newline at end of file +*.idea +.DS_Store +*.zip \ No newline at end of file diff --git a/lib/gene-plugin-1.0-SNAPSHOT.jar b/lib/gene-plugin-1.0-SNAPSHOT.jar deleted file mode 100644 index 9529189..0000000 Binary files a/lib/gene-plugin-1.0-SNAPSHOT.jar and /dev/null differ diff --git a/lib/javaparser-core-3.6.25.jar b/lib/javaparser-core-3.6.25.jar deleted file mode 100644 index 9e0cea1..0000000 Binary files a/lib/javaparser-core-3.6.25.jar and /dev/null differ diff --git a/lib/mybatis-generator-core-1.3.7.jar b/lib/mybatis-generator-core-1.3.7.jar deleted file mode 100644 index 1e4f08d..0000000 Binary files a/lib/mybatis-generator-core-1.3.7.jar and /dev/null differ diff --git a/lib/mybatis-generator-core-1.4.0.jar b/lib/mybatis-generator-core-1.4.0.jar new file mode 100755 index 0000000..0409caa Binary files /dev/null and b/lib/mybatis-generator-core-1.4.0.jar differ diff --git a/mybatis-generator-plus.iml b/mybatis-generator-plus.iml deleted file mode 100644 index 7d02a3b..0000000 --- a/mybatis-generator-plus.iml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/resources/META-INF/plugin.xml b/resources/META-INF/plugin.xml index 248da68..2a0ecb9 100644 --- a/resources/META-INF/plugin.xml +++ b/resources/META-INF/plugin.xml @@ -6,6 +6,19 @@ +
  • + 支持DataGrip
    + 支持自定义domain后缀
    + 支持自动识别mysql版本
    + 支持xml默认包设置
    + 支持选择mgb运行时
    + project tools 配置界面去除package相关配置
    + 数据库用户名密码改为明文存储在插件持久化xml中(解决每次都要输入主机登录密码的烦恼)
    +
  • + + ]]> +
  • Integrate with the Idea Database tool
    @@ -92,13 +105,16 @@ ]]> - + - com.intellij.database + com.intellij.modules.platform + com.intellij.database + + diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/action/MainAction.java b/src/com/github/leecho/idea/plugin/mybatis/generator/action/MainAction.java index 6fc6256..3b5e102 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/action/MainAction.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/action/MainAction.java @@ -39,9 +39,6 @@ public void actionPerformed(AnActionEvent e) { } GenerateSettingUI ui = new GenerateSettingUI(e); ui.show(); - /*if (ui.showAndGet()) { - ui.generate(); - }*/ } } diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/enums/MbgJavaClientConfigTypeEnum.java b/src/com/github/leecho/idea/plugin/mybatis/generator/enums/MbgJavaClientConfigTypeEnum.java new file mode 100644 index 0000000..2f82527 --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/enums/MbgJavaClientConfigTypeEnum.java @@ -0,0 +1,59 @@ +package com.github.leecho.idea.plugin.mybatis.generator.enums; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public enum MbgJavaClientConfigTypeEnum { + MAPPER("MAPPER", "包含 Mapper 接口和 XML 文件,不包含注解"), + XMLMAPPER("XMLMAPPER", "包含 Mapper 接口和 XML 文件,不包含注解"), + ANNOTATEDMAPPER("ANNOTATEDMAPPER", "包含 Mapper 接口和 SqlProvider 辅助类,全注解,不包含 XML 文件"), + MIXEDMAPPER("MIXEDMAPPER", "包含 Mapper 接口和 XML 文件,简单的 CRUD 使用注解,高级条件查询使用 XML 文件"), + ; + private String name; + private String desc; + + MbgJavaClientConfigTypeEnum(String name, String desc) { + this.name = name; + this.desc = desc; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public static List getValuesByTargetRuntime(MbgTargetRuntimeEnum runtimeEnum) { + List list = new ArrayList<>(); + switch (runtimeEnum) { + case MY_BATIS3_DYNAMIC_SQL: + case MY_BATIS3_KOTLIN: + break; + case MY_BATIS3: + list = Arrays.stream(MbgJavaClientConfigTypeEnum.values()) + .map(MbgJavaClientConfigTypeEnum::getName).collect( + Collectors.toList()); + break; + case MY_BATIS3_SIMPLE: + list = Arrays.stream(MbgJavaClientConfigTypeEnum.values()) + .filter(i -> !Objects.equals(i, MbgJavaClientConfigTypeEnum.MIXEDMAPPER)) + .map(MbgJavaClientConfigTypeEnum::getName).collect( + Collectors.toList()); + break; + } + return list; + } +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/enums/MbgTargetRuntimeEnum.java b/src/com/github/leecho/idea/plugin/mybatis/generator/enums/MbgTargetRuntimeEnum.java new file mode 100644 index 0000000..82cba0b --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/enums/MbgTargetRuntimeEnum.java @@ -0,0 +1,43 @@ +package com.github.leecho.idea.plugin.mybatis.generator.enums; + +import java.util.Objects; + +public enum MbgTargetRuntimeEnum { + MY_BATIS3_DYNAMIC_SQL("MyBatis3DynamicSql","动态sql"), + MY_BATIS3_KOTLIN("MyBatis3Kotlin","支持Kotlin语言"), + MY_BATIS3("MyBatis3","最基础的"), + MY_BATIS3_SIMPLE("MyBatis3Simple","简单的(没有example)"), + ; + private String name; + private String desc; + + MbgTargetRuntimeEnum(String name, String desc) { + this.name = name; + this.desc = desc; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public static MbgTargetRuntimeEnum getByName(String name){ + for (MbgTargetRuntimeEnum value : MbgTargetRuntimeEnum.values()) { + if (Objects.equals(name,value.name)) { + return value; + } + } + return null; + } +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/enums/PackageTypeEnum.java b/src/com/github/leecho/idea/plugin/mybatis/generator/enums/PackageTypeEnum.java new file mode 100644 index 0000000..12f7395 --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/enums/PackageTypeEnum.java @@ -0,0 +1,21 @@ +package com.github.leecho.idea.plugin.mybatis.generator.enums; + +public enum PackageTypeEnum { + SOURCE_ROOT(0, "sourceRoot"), + RESOURCE_ROOT(1, "resourceRoot"), + BASE(2, "basePackage"), + DOMAIN(3, "domainPackage"), + MAPPER(4, "mapperPackage"), + EXAMPLE(5, "examplePackage"), + XML(6, "xmlPackage"), + ; + private Integer code; + private String desc; + + PackageTypeEnum(Integer code, String desc) { + this.code = code; + this.desc = desc; + } + + +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/generate/GenerateCallback.java b/src/com/github/leecho/idea/plugin/mybatis/generator/generate/GenerateCallback.java index 1e21fae..cf82adb 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/generate/GenerateCallback.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/generate/GenerateCallback.java @@ -30,6 +30,7 @@ public void saveStarted(int i) { @Override public void startTask(String s) { System.out.println("Start Task: " + s); + indicator.setIndeterminate(false); indicator.setText(s); indicator.setFraction(indicator.getFraction() + 0.1); } diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MergeableShellCallback.java b/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MergeableShellCallback.java deleted file mode 100644 index 7987332..0000000 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MergeableShellCallback.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.github.leecho.idea.plugin.mybatis.generator.generate; - -import com.github.leecho.idea.plugin.mybatis.generator.util.JavaFileMerger; -import org.mybatis.generator.exception.ShellException; -import org.mybatis.generator.internal.DefaultShellCallback; - -import java.io.File; -import java.io.FileNotFoundException; - -/** - * @author LIQIU - */ -public class MergeableShellCallback extends DefaultShellCallback { - - public MergeableShellCallback(boolean overwrite) { - super(overwrite); - } - - @Override - public boolean isMergeSupported() { - return true; - } - - @Override - public String mergeJavaFile(String newFileSource, File existingFile, String[] javadocTags, String fileEncoding) throws ShellException { - String filePath = existingFile.getAbsolutePath().replace(".java", ""); - if (filePath.endsWith("Mapper")) { - try { - return new JavaFileMerger().getNewJavaFile(newFileSource, existingFile.getAbsolutePath()); - } catch (FileNotFoundException e) { - throw new ShellException(e); - } - } else { - return newFileSource; - } - } -} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MyBatisCodeGenerator.java b/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MyBatisCodeGenerator.java deleted file mode 100644 index cf69e92..0000000 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MyBatisCodeGenerator.java +++ /dev/null @@ -1,417 +0,0 @@ -package com.github.leecho.idea.plugin.mybatis.generator.generate; - -import com.github.leecho.idea.plugin.mybatis.generator.util.XmlFileMerger; -import org.mybatis.generator.api.GeneratedJavaFile; -import org.mybatis.generator.api.GeneratedXmlFile; -import org.mybatis.generator.api.ProgressCallback; -import org.mybatis.generator.api.ShellCallback; -import org.mybatis.generator.codegen.RootClassInfo; -import org.mybatis.generator.config.Configuration; -import org.mybatis.generator.config.Context; -import org.mybatis.generator.config.MergeConstants; -import org.mybatis.generator.exception.InvalidConfigurationException; -import org.mybatis.generator.exception.ShellException; -import org.mybatis.generator.internal.DefaultShellCallback; -import org.mybatis.generator.internal.NullProgressCallback; -import org.mybatis.generator.internal.ObjectFactory; - -import java.io.*; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.mybatis.generator.internal.util.ClassloaderUtility.getCustomClassloader; -import static org.mybatis.generator.internal.util.messages.Messages.getString; - -/** - * This class is the main interface to MyBatis generator. A typical execution of the tool involves these steps: - * - *
      - *
    1. Create a Configuration object. The Configuration can be the result of a parsing the XML configuration file, or it - * can be created solely in Java.
    2. - *
    3. Create a MyBatisCodeGenerator object
    4. - *
    5. Call one of the generate() methods
    6. - *
    - * - * @author Jeff Butler - * @see org.mybatis.generator.config.xml.ConfigurationParser - */ -public class MyBatisCodeGenerator { - - /** - * The configuration. - */ - private Configuration configuration; - - /** - * The shell callback. - */ - private ShellCallback shellCallback; - - /** - * The generated java files. - */ - private List generatedJavaFiles; - - /** - * The generated xml files. - */ - private List generatedXmlFiles; - - /** - * The warnings. - */ - private List warnings; - - /** - * The projects. - */ - private Set projects; - - /** - * Constructs a MyBatisCodeGenerator object. - * - * @param configuration The configuration for this invocation - * @param shellCallback an instance of a ShellCallback interface. You may specify - * null in which case the DefaultShellCallback will - * be used. - * @param warnings Any warnings generated during execution will be added to this - * list. Warnings do not affect the running of the tool, but they - * may affect the results. A typical warning is an unsupported - * data type. In that case, the column will be ignored and - * generation will continue. You may specify null if - * you do not want warnings returned. - * @throws InvalidConfigurationException if the specified configuration is invalid - */ - public MyBatisCodeGenerator(Configuration configuration, ShellCallback shellCallback, - List warnings) throws InvalidConfigurationException { - super(); - if (configuration == null) { - throw new IllegalArgumentException(getString("RuntimeError.2")); //$NON-NLS-1$ - } else { - this.configuration = configuration; - } - - if (shellCallback == null) { - this.shellCallback = new DefaultShellCallback(false); - } else { - this.shellCallback = shellCallback; - } - - if (warnings == null) { - this.warnings = new ArrayList(); - } else { - this.warnings = warnings; - } - generatedJavaFiles = new ArrayList(); - generatedXmlFiles = new ArrayList(); - projects = new HashSet(); - - this.configuration.validate(); - } - - /** - * This is the main method for generating code. This method is long running, but progress can be provided and the - * method can be canceled through the ProgressCallback interface. This version of the method runs all configured - * contexts. - * - * @param callback an instance of the ProgressCallback interface, or null if you do not require progress - * information - * @throws SQLException the SQL exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException if the method is canceled through the ProgressCallback - */ - public void generate(ProgressCallback callback) throws SQLException, - IOException, InterruptedException { - generate(callback, null, null, true); - } - - /** - * This is the main method for generating code. This method is long running, but progress can be provided and the - * method can be canceled through the ProgressCallback interface. - * - * @param callback an instance of the ProgressCallback interface, or null if you do not require progress - * information - * @param contextIds a set of Strings containing context ids to run. Only the contexts with an id specified in this list - * will be run. If the list is null or empty, than all contexts are run. - * @throws SQLException the SQL exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException if the method is canceled through the ProgressCallback - */ - public void generate(ProgressCallback callback, Set contextIds) - throws SQLException, IOException, InterruptedException { - generate(callback, contextIds, null, true); - } - - /** - * This is the main method for generating code. This method is long running, but progress can be provided and the - * method can be cancelled through the ProgressCallback interface. - * - * @param callback an instance of the ProgressCallback interface, or null if you do not require progress - * information - * @param contextIds a set of Strings containing context ids to run. Only the contexts with an id specified in this list - * will be run. If the list is null or empty, than all contexts are run. - * @param fullyQualifiedTableNames a set of table names to generate. The elements of the set must be Strings that exactly match what's - * specified in the configuration. For example, if table name = "foo" and schema = "bar", then the fully - * qualified table name is "foo.bar". If the Set is null or empty, then all tables in the configuration - * will be used for code generation. - * @throws SQLException the SQL exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException if the method is canceled through the ProgressCallback - */ - public void generate(ProgressCallback callback, Set contextIds, - Set fullyQualifiedTableNames) throws SQLException, - IOException, InterruptedException { - generate(callback, contextIds, fullyQualifiedTableNames, true); - } - - /** - * This is the main method for generating code. This method is long running, but progress can be provided and the - * method can be cancelled through the ProgressCallback interface. - * - * @param callback an instance of the ProgressCallback interface, or null if you do not require progress - * information - * @param contextIds a set of Strings containing context ids to run. Only the contexts with an id specified in this list - * will be run. If the list is null or empty, than all contexts are run. - * @param fullyQualifiedTableNames a set of table names to generate. The elements of the set must be Strings that exactly match what's - * specified in the configuration. For example, if table name = "foo" and schema = "bar", then the fully - * qualified table name is "foo.bar". If the Set is null or empty, then all tables in the configuration - * will be used for code generation. - * @param writeFiles if true, then the generated files will be written to disk. If false, - * then the generator runs but nothing is written - * @throws SQLException the SQL exception - * @throws IOException Signals that an I/O exception has occurred. - * @throws InterruptedException if the method is canceled through the ProgressCallback - */ - public void generate(ProgressCallback callback, Set contextIds, - Set fullyQualifiedTableNames, boolean writeFiles) throws SQLException, - IOException, InterruptedException { - - if (callback == null) { - callback = new NullProgressCallback(); - } - - generatedJavaFiles.clear(); - generatedXmlFiles.clear(); - ObjectFactory.reset(); - RootClassInfo.reset(); - - // calculate the contexts to run - List contextsToRun; - if (contextIds == null || contextIds.size() == 0) { - contextsToRun = configuration.getContexts(); - } else { - contextsToRun = new ArrayList(); - for (Context context : configuration.getContexts()) { - if (contextIds.contains(context.getId())) { - contextsToRun.add(context); - } - } - } - - // setup custom classloader if required - if (configuration.getClassPathEntries().size() > 0) { - ClassLoader classLoader = getCustomClassloader(configuration.getClassPathEntries()); - ObjectFactory.addExternalClassLoader(classLoader); - } - - // now run the introspections... - int totalSteps = 0; - for (Context context : contextsToRun) { - totalSteps += context.getIntrospectionSteps(); - } - callback.introspectionStarted(totalSteps); - - for (Context context : contextsToRun) { - context.introspectTables(callback, warnings, - fullyQualifiedTableNames); - } - - // now run the generates - totalSteps = 0; - for (Context context : contextsToRun) { - totalSteps += context.getGenerationSteps(); - } - callback.generationStarted(totalSteps); - - for (Context context : contextsToRun) { - context.generateFiles(callback, generatedJavaFiles, - generatedXmlFiles, warnings); - } - - // now save the files - if (writeFiles) { - callback.saveStarted(generatedXmlFiles.size() - + generatedJavaFiles.size()); - - for (GeneratedXmlFile gxf : generatedXmlFiles) { - projects.add(gxf.getTargetProject()); - writeGeneratedXmlFile(gxf, callback); - } - - for (GeneratedJavaFile gjf : generatedJavaFiles) { - projects.add(gjf.getTargetProject()); - writeGeneratedJavaFile(gjf, callback); - } - - for (String project : projects) { - shellCallback.refreshProject(project); - } - } - - callback.done(); - } - - private void writeGeneratedJavaFile(GeneratedJavaFile gjf, ProgressCallback callback) - throws InterruptedException, IOException { - File targetFile; - String source; - try { - File directory = shellCallback.getDirectory(gjf - .getTargetProject(), gjf.getTargetPackage()); - targetFile = new File(directory, gjf.getFileName()); - if (targetFile.exists()) { - if (shellCallback.isMergeSupported()) { - source = shellCallback.mergeJavaFile(gjf .getFormattedContent(), - targetFile, - MergeConstants.OLD_ELEMENT_TAGS, - gjf.getFileEncoding()); - } else if (shellCallback.isOverwriteEnabled()) { - source = gjf.getFormattedContent(); - warnings.add(getString("Warning.11", //$NON-NLS-1$ - targetFile.getAbsolutePath())); - } else { - source = gjf.getFormattedContent(); - targetFile = getUniqueFileName(directory, gjf - .getFileName()); - warnings.add(getString( - "Warning.2", targetFile.getAbsolutePath())); //$NON-NLS-1$ - } - } else { - source = gjf.getFormattedContent(); - } - - callback.checkCancel(); - callback.startTask(getString( - "Progress.15", targetFile.getName())); //$NON-NLS-1$ - writeFile(targetFile, source, gjf.getFileEncoding()); - } catch (ShellException e) { - warnings.add(e.getMessage()); - } - } - - private void writeGeneratedXmlFile(GeneratedXmlFile gxf, ProgressCallback callback) - throws InterruptedException, IOException { - File targetFile; - String source; - try { - File directory = shellCallback.getDirectory(gxf - .getTargetProject(), gxf.getTargetPackage()); - targetFile = new File(directory, gxf.getFileName()); - if (targetFile.exists()) { - if (gxf.isMergeable()) { - source = XmlFileMerger.getMergedSource(gxf, - targetFile); - } else if (shellCallback.isOverwriteEnabled()) { - source = gxf.getFormattedContent(); - warnings.add(getString("Warning.11", //$NON-NLS-1$ - targetFile.getAbsolutePath())); - } else { - source = gxf.getFormattedContent(); - targetFile = getUniqueFileName(directory, gxf - .getFileName()); - warnings.add(getString( - "Warning.2", targetFile.getAbsolutePath())); //$NON-NLS-1$ - } - } else { - source = gxf.getFormattedContent(); - } - - callback.checkCancel(); - callback.startTask(getString( - "Progress.15", targetFile.getName())); //$NON-NLS-1$ - writeFile(targetFile, source, "UTF-8"); //$NON-NLS-1$ - } catch (ShellException e) { - warnings.add(e.getMessage()); - } - } - - /** - * Writes, or overwrites, the contents of the specified file. - * - * @param file the file - * @param content the content - * @param fileEncoding the file encoding - * @throws IOException Signals that an I/O exception has occurred. - */ - private void writeFile(File file, String content, String fileEncoding) throws IOException { - FileOutputStream fos = new FileOutputStream(file, false); - OutputStreamWriter osw; - if (fileEncoding == null) { - osw = new OutputStreamWriter(fos); - } else { - osw = new OutputStreamWriter(fos, fileEncoding); - } - - BufferedWriter bw = new BufferedWriter(osw); - bw.write(content); - bw.close(); - } - - /** - * Gets the unique file name. - * - * @param directory the directory - * @param fileName the file name - * @return the unique file name - */ - private File getUniqueFileName(File directory, String fileName) { - File answer = null; - - // try up to 1000 times to generate a unique file name - StringBuilder sb = new StringBuilder(); - for (int i = 1; i < 1000; i++) { - sb.setLength(0); - sb.append(fileName); - sb.append('.'); - sb.append(i); - - File testFile = new File(directory, sb.toString()); - if (!testFile.exists()) { - answer = testFile; - break; - } - } - - if (answer == null) { - throw new RuntimeException(getString( - "RuntimeError.3", directory.getAbsolutePath())); //$NON-NLS-1$ - } - - return answer; - } - - /** - * Returns the list of generated Java files after a call to one of the generate methods. - * This is useful if you prefer to process the generated files yourself and do not want - * the generator to write them to disk. - * - * @return the list of generated Java files - */ - public List getGeneratedJavaFiles() { - return generatedJavaFiles; - } - - /** - * Returns the list of generated XML files after a call to one of the generate methods. - * This is useful if you prefer to process the generated files yourself and do not want - * the generator to write them to disk. - * - * @return the list of generated XML files - */ - public List getGeneratedXmlFiles() { - return generatedXmlFiles; - } -} \ No newline at end of file diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MyBatisGenerateCommand.java b/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MyBatisGenerateCommand.java index 866ebde..f7962f7 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MyBatisGenerateCommand.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/generate/MyBatisGenerateCommand.java @@ -1,10 +1,8 @@ package com.github.leecho.idea.plugin.mybatis.generator.generate; -import cn.kt.DbRemarksCommentGenerator; +import com.github.leecho.idea.plugin.mybatis.generator.model.ConnectionConfig; import com.github.leecho.idea.plugin.mybatis.generator.model.TableConfig; -import com.intellij.credentialStore.CredentialAttributes; -import com.intellij.database.model.RawConnectionConfig; -import com.intellij.ide.passwordSafe.PasswordSafe; +import com.github.leecho.idea.plugin.mybatis.generator.plugin.DbRemarksCommentGenerator; import com.intellij.notification.*; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.progress.ProgressIndicator; @@ -22,6 +20,8 @@ import com.github.leecho.idea.plugin.mybatis.generator.model.DbType; import com.github.leecho.idea.plugin.mybatis.generator.setting.MyBatisGeneratorConfiguration; import com.github.leecho.idea.plugin.mybatis.generator.util.StringUtils; +import java.nio.charset.StandardCharsets; +import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.api.ShellCallback; import org.mybatis.generator.config.*; import org.mybatis.generator.internal.DefaultShellCallback; @@ -60,7 +60,7 @@ public MyBatisGenerateCommand(TableConfig tableConfig) { * @param connectionConfig * @throws Exception */ - public void execute(Project project, RawConnectionConfig connectionConfig) { + public void execute(Project project, ConnectionConfig connectionConfig) { this.myBatisGeneratorConfiguration = MyBatisGeneratorConfiguration.getInstance(project); saveConfig();//执行前 先保存一份当前配置 @@ -87,12 +87,11 @@ public void execute(Project project, RawConnectionConfig connectionConfig) { configuration.addContext(context); context.setId("myid"); - context.addProperty("autoDelimitKeywords", "true"); - context.addProperty("beginningDelimiter", "`"); - context.addProperty("endingDelimiter", "`"); - context.addProperty("javaFileEncoding", "UTF-8"); - context.addProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING, "UTF-8"); - context.setTargetRuntime("MyBatis3"); + context.addProperty(PropertyRegistry.CONTEXT_AUTO_DELIMIT_KEYWORDS, "true"); + context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`"); + context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`"); + context.addProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING, StandardCharsets.UTF_8.name()); + context.setTargetRuntime(tableConfig.getMgbTargetRuntime()); JDBCConnectionConfiguration jdbcConfig = buildJdbcConfig(); if (jdbcConfig == null) { @@ -115,17 +114,12 @@ public void execute(Project project, RawConnectionConfig connectionConfig) { createFolderForNeed(this.tableConfig); List warnings = new ArrayList<>(); // override=true - ShellCallback shellCallback; - if (this.tableConfig.isOverride()) { - shellCallback = new DefaultShellCallback(true); - } else { - shellCallback = new MergeableShellCallback(true); - } + ShellCallback shellCallback= new DefaultShellCallback(this.tableConfig.isOverride()); Set fullyQualifiedTables = new HashSet<>(); Set contexts = new HashSet<>(); try { - MyBatisCodeGenerator myBatisCodeGenerator = new MyBatisCodeGenerator(configuration, shellCallback, warnings); + MyBatisGenerator myBatisCodeGenerator = new MyBatisGenerator(configuration, shellCallback, warnings); StatusBar statusBar = WindowManager.getInstance().getStatusBar(project); Balloon balloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder("Generating Code...", MessageType.INFO, null) @@ -146,10 +140,10 @@ public void run(ProgressIndicator indicator) { NotificationGroup balloonNotifications = new NotificationGroup("Mybatis Generator Plus", NotificationDisplayType.STICKY_BALLOON, true); List result = myBatisCodeGenerator.getGeneratedJavaFiles().stream() - .map(generatedJavaFile -> String.format("%s", getRelativePath(project), MyBatisGenerateCommand.this.tableConfig.getSourcePath(), generatedJavaFile.getTargetPackage().replace(".", "/"), generatedJavaFile.getFileName(), generatedJavaFile.getFileName())) + .map(generatedJavaFile -> String.format("%s", getRelativePath(project), MyBatisGenerateCommand.this.tableConfig.getSourcePath(), generatedJavaFile.getTargetPackage().replace(".", File.separator), generatedJavaFile.getFileName(), generatedJavaFile.getFileName())) .collect(Collectors.toList()); result.addAll(myBatisCodeGenerator.getGeneratedXmlFiles().stream() - .map(generatedXmlFile -> String.format("%s", getRelativePath(project).replace(project.getBasePath() + "/", ""), MyBatisGenerateCommand.this.tableConfig.getResourcePath(), generatedXmlFile.getTargetPackage().replace(".", "/"), generatedXmlFile.getFileName(), generatedXmlFile.getFileName())) + .map(generatedXmlFile -> String.format("%s", getRelativePath(project).replace(project.getBasePath() + File.separator, ""), MyBatisGenerateCommand.this.tableConfig.getResourcePath(), generatedXmlFile.getTargetPackage().replace(".", File.separator), generatedXmlFile.getFileName(), generatedXmlFile.getFileName())) .collect(Collectors.toList())); Notification notification = balloonNotifications.createNotification("Generate Successfully", "" + String.join("
    ", result) + "", NotificationType.INFORMATION, (notification1, hyperlinkEvent) -> { if (hyperlinkEvent.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { @@ -160,7 +154,7 @@ public void run(ProgressIndicator indicator) { } catch (Exception e) { e.printStackTrace(); balloon.hide(); - Notification notification = new Notification("Mybatis Generator Plus", null, NotificationType.ERROR); + Notification notification = new Notification("Mybatis Generator Plus", "", NotificationType.ERROR); notification.setTitle("Generate Failed"); notification.setContent("Cause:" + e.getMessage()); Notifications.Bus.notify(notification); @@ -181,7 +175,7 @@ private String getRelativePath(Project project) { if (tableConfig.getModuleRootPath().equals(project.getBasePath())) { return ""; } else { - return tableConfig.getModuleRootPath().replace(project.getBasePath() + "/", "") + "/"; + return tableConfig.getModuleRootPath().replace(project.getBasePath() + File.separator, "") + File.separator; } } @@ -194,8 +188,8 @@ private String getRelativePath(Project project) { private void createFolderForNeed(TableConfig tableConfig) { - String sourcePath = tableConfig.getModuleRootPath() + "/" + tableConfig.getSourcePath() + "/"; - String resourcePath = tableConfig.getModuleRootPath() + "/" + tableConfig.getResourcePath() + "/"; + String sourcePath = tableConfig.getModuleRootPath() + File.separator + tableConfig.getSourcePath() + File.separator; + String resourcePath = tableConfig.getModuleRootPath() + File.separator + tableConfig.getResourcePath() + File.separator; File sourceFile = new File(sourcePath); if (!sourceFile.exists() && !sourceFile.isDirectory()) { @@ -217,15 +211,8 @@ private void saveConfig() { if (historyConfigList == null) { historyConfigList = new HashMap<>(); } - - String daoName = tableConfig.getMapperName(); - String modelName = tableConfig.getDomainName(); - String daoPostfix = daoName.replace(modelName, ""); - tableConfig.setMapperPostfix(daoPostfix); - historyConfigList.put(tableConfig.getName(), tableConfig); myBatisGeneratorConfiguration.setTableConfigs(historyConfigList); - } /** @@ -241,16 +228,13 @@ private JDBCConnectionConfiguration buildJdbcConfig() { jdbcConfig.addProperty("useInformationSchema","true"); Map users = myBatisGeneratorConfiguration.getCredentials(); - //if (users != null && users.containsKey(url)) { Credential credential = users.get(url); username = credential.getUsername(); - CredentialAttributes credentialAttributes = new CredentialAttributes("mybatis-generator-" + url, username, this.getClass(), false); - String password = PasswordSafe.getInstance().getPassword(credentialAttributes); jdbcConfig.setUserId(username); - jdbcConfig.setPassword(password); + jdbcConfig.setPassword(credential.getPwd()); Boolean mySQL_8 = tableConfig.isMysql8(); if (mySQL_8) { @@ -263,11 +247,6 @@ private JDBCConnectionConfiguration buildJdbcConfig() { jdbcConfig.setDriverClass(driverClass); jdbcConfig.setConnectionURL(url); return jdbcConfig; - /*} else { - DatabaseCredentialUI databaseCredentialUI = new DatabaseCredentialUI(driverClass, url, anActionEvent, tableConfig); - return null; - }*/ - } /** @@ -283,7 +262,7 @@ private TableConfiguration buildTableConfig(Context context) { String schema; if (databaseType.equals(DbType.MySQL.name())) { - String[] name_split = url.split("/"); + String[] name_split = url.split(File.separator); schema = name_split[name_split.length - 1]; tableConfig.setSchema(schema); } else if (databaseType.equals(DbType.Oracle.name())) { @@ -291,7 +270,7 @@ private TableConfiguration buildTableConfig(Context context) { schema = name_split[name_split.length - 1]; tableConfig.setCatalog(schema); } else { - String[] name_split = url.split("/"); + String[] name_split = url.split(File.separator); schema = name_split[name_split.length - 1]; tableConfig.setCatalog(schema); } @@ -329,7 +308,7 @@ private TableConfiguration buildTableConfig(Context context) { }); } - if ("org.postgresql.Driver".equals(driverClass)) { + if (DbType.PostgreSQL.getDriverClass().equals(driverClass)) { tableConfig.setDelimitIdentifiers(true); } @@ -344,11 +323,11 @@ private TableConfiguration buildTableConfig(Context context) { //当使用SelectKey时,Mybatis会使用SelectKeyGenerator,INSERT之后,多发送一次查询语句,获得主键值 //在上述读写分离被代理的情况下,会得不到正确的主键 } - tableConfig.setGeneratedKey(new GeneratedKey(this.tableConfig.getPrimaryKey(), dbType, true, null)); + tableConfig.setGeneratedKey(new GeneratedKey(this.tableConfig.getPrimaryKey(), dbType, true, "post")); } if (this.tableConfig.isUseActualColumnNames()) { - tableConfig.addProperty("useActualColumnNames", "true"); + tableConfig.addProperty(PropertyRegistry.TABLE_USE_ACTUAL_COLUMN_NAMES, "true"); } if (this.tableConfig.isUseTableNameAlias()) { @@ -366,17 +345,17 @@ private TableConfiguration buildTableConfig(Context context) { */ private JavaModelGeneratorConfiguration buildModelConfig() { String projectFolder = tableConfig.getModuleRootPath(); - String entityPackage = tableConfig.getDomainPackage(); + String modelPackage = tableConfig.getDomainPackage(); String sourcePath = tableConfig.getSourcePath(); JavaModelGeneratorConfiguration modelConfig = new JavaModelGeneratorConfiguration(); - if (!StringUtils.isEmpty(entityPackage)) { - modelConfig.setTargetPackage(entityPackage); + if (!StringUtils.isEmpty(modelPackage)) { + modelConfig.setTargetPackage(modelPackage); } else { modelConfig.setTargetPackage(""); } - modelConfig.setTargetProject(projectFolder + "/" + sourcePath + "/"); + modelConfig.setTargetProject(projectFolder + File.separator + sourcePath + File.separator); return modelConfig; } @@ -399,16 +378,7 @@ private SqlMapGeneratorConfiguration buildMapperXmlConfig() { mapperConfig.setTargetPackage(""); } - mapperConfig.setTargetProject(projectFolder + "/" + resourcePath + "/"); - - //14 - if (tableConfig.isOverride()) { - String mappingXMLFilePath = getMappingXMLFilePath(tableConfig); - File mappingXMLFile = new File(mappingXMLFilePath); - if (mappingXMLFile.exists()) { - mappingXMLFile.delete(); - } - } + mapperConfig.setTargetProject(projectFolder + File.separator + resourcePath + File.separator); return mapperConfig; } @@ -425,7 +395,7 @@ private JavaClientGeneratorConfiguration buildMapperConfig() { String mapperPath = tableConfig.getSourcePath(); JavaClientGeneratorConfiguration mapperConfig = new JavaClientGeneratorConfiguration(); - mapperConfig.setConfigurationType("XMLMAPPER"); + mapperConfig.setConfigurationType(tableConfig.getMgbJavaClientConfigType()); mapperConfig.setTargetPackage(mapperPackage); if (!StringUtils.isEmpty(mapperPackage)) { @@ -434,7 +404,7 @@ private JavaClientGeneratorConfiguration buildMapperConfig() { mapperConfig.setTargetPackage(""); } - mapperConfig.setTargetProject(projectFolder + "/" + mapperPath + "/"); + mapperConfig.setTargetProject(projectFolder + File.separator + mapperPath + File.separator); return mapperConfig; } @@ -446,10 +416,9 @@ private JavaClientGeneratorConfiguration buildMapperConfig() { */ private CommentGeneratorConfiguration buildCommentConfig() { CommentGeneratorConfiguration commentConfig = new CommentGeneratorConfiguration(); - commentConfig.setConfigurationType(DbRemarksCommentGenerator.class.getName()); - if (tableConfig.isComment()) { - commentConfig.addProperty("columnRemarks", "true"); + commentConfig.addProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS, "true"); + commentConfig.addProperty(PropertyRegistry.COMMENT_GENERATOR_DATE_FORMAT, "yyyy-MM-dd HH:mm:ss"); } if (tableConfig.isAnnotation()) { commentConfig.addProperty("annotations", "true"); @@ -495,12 +464,6 @@ private void addPluginConfiguration(Context context) { } context.addPluginConfiguration(lombokPlugin); } - if (tableConfig.isSwaggerAnnotation()) { - PluginConfiguration swaggerPlugin = new PluginConfiguration(); - swaggerPlugin.addProperty("type", "com.github.leecho.idea.plugin.mybatis.generator.plugin.SwaggerPlugin"); - swaggerPlugin.setConfigurationType("com.github.leecho.idea.plugin.mybatis.generator.plugin.SwaggerPlugin"); - context.addPluginConfiguration(swaggerPlugin); - } if (tableConfig.isUseExample()) { PluginConfiguration renameExamplePlugin = new PluginConfiguration(); @@ -510,43 +473,22 @@ private void addPluginConfiguration(Context context) { context.addPluginConfiguration(renameExamplePlugin); } - - // limit/offset插件 - if (tableConfig.isOffsetLimit()) { - if (DbType.MySQL.name().equals(databaseType) - || DbType.PostgreSQL.name().equals(databaseType)) { - PluginConfiguration mySQLLimitPlugin = new PluginConfiguration(); - mySQLLimitPlugin.addProperty("type", "cn.kt.MySQLLimitPlugin"); - mySQLLimitPlugin.setConfigurationType("cn.kt.MySQLLimitPlugin"); - context.addPluginConfiguration(mySQLLimitPlugin); - } - } - + JavaTypeResolverConfiguration javaTypeResolverPlugin = new JavaTypeResolverConfiguration(); + javaTypeResolverPlugin.setConfigurationType("com.github.leecho.idea.plugin.mybatis.generator.plugin.MyJavaTypeResolverDefaultImpl"); + javaTypeResolverPlugin.addProperty(PropertyRegistry.TYPE_RESOLVER_FORCE_BIG_DECIMALS,"true"); //for JSR310 if (tableConfig.isJsr310Support()) { - JavaTypeResolverConfiguration javaTypeResolverPlugin = new JavaTypeResolverConfiguration(); - javaTypeResolverPlugin.setConfigurationType("cn.kt.JavaTypeResolverJsr310Impl"); - context.setJavaTypeResolverConfiguration(javaTypeResolverPlugin); - } - - //forUpdate 插件 - if (tableConfig.isNeedForUpdate()) { - if (DbType.MySQL.name().equals(databaseType) - || DbType.PostgreSQL.name().equals(databaseType)) { - PluginConfiguration mySQLForUpdatePlugin = new PluginConfiguration(); - mySQLForUpdatePlugin.addProperty("type", "cn.kt.MySQLForUpdatePlugin"); - mySQLForUpdatePlugin.setConfigurationType("cn.kt.MySQLForUpdatePlugin"); - context.addPluginConfiguration(mySQLForUpdatePlugin); - } + javaTypeResolverPlugin.addProperty(PropertyRegistry.TYPE_RESOLVER_USE_JSR310_TYPES,"true"); } + context.setJavaTypeResolverConfiguration(javaTypeResolverPlugin); //repository 插件 if (tableConfig.isAnnotationDAO()) { if (DbType.MySQL.name().equals(databaseType) || DbType.PostgreSQL.name().equals(databaseType)) { PluginConfiguration repositoryPlugin = new PluginConfiguration(); - repositoryPlugin.addProperty("type", "cn.kt.RepositoryPlugin"); - repositoryPlugin.setConfigurationType("cn.kt.RepositoryPlugin"); + repositoryPlugin.addProperty("type", "com.github.leecho.idea.plugin.mybatis.generator.plugin.RepositoryPlugin"); + repositoryPlugin.setConfigurationType("com.github.leecho.idea.plugin.mybatis.generator.plugin.RepositoryPlugin"); context.addPluginConfiguration(repositoryPlugin); } } @@ -556,35 +498,11 @@ private void addPluginConfiguration(Context context) { if (DbType.MySQL.name().equals(databaseType) || DbType.PostgreSQL.name().equals(databaseType)) { PluginConfiguration commonDAOInterfacePlugin = new PluginConfiguration(); - commonDAOInterfacePlugin.addProperty("type", "cn.kt.CommonDAOInterfacePlugin"); - commonDAOInterfacePlugin.setConfigurationType("cn.kt.CommonDAOInterfacePlugin"); + commonDAOInterfacePlugin.addProperty("type", "com.github.leecho.idea.plugin.mybatis.generator.plugin.CommonDAOInterfacePlugin"); + commonDAOInterfacePlugin.setConfigurationType("com.github.leecho.idea.plugin.mybatis.generator.plugin.CommonDAOInterfacePlugin"); context.addPluginConfiguration(commonDAOInterfacePlugin); } } } - - /** - * 获取xml文件路径 用以删除之前的xml - * - * @param tableConfig - * @return - */ - private String getMappingXMLFilePath(TableConfig tableConfig) { - StringBuilder sb = new StringBuilder(); - String mappingXMLPackage = tableConfig.getXmlPackage(); - String xmlMvnPath = tableConfig.getResourcePath(); - sb.append(tableConfig.getModuleRootPath() + "/" + xmlMvnPath + "/"); - - if (!StringUtils.isEmpty(mappingXMLPackage)) { - sb.append(mappingXMLPackage.replace(".", "/")).append("/"); - } - if (!StringUtils.isEmpty(tableConfig.getMapperName())) { - sb.append(tableConfig.getMapperName()).append(".xml"); - } else { - sb.append(tableConfig.getDomainName()).append("Mapper.xml"); - } - - return sb.toString(); - } } diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/model/ConnectionConfig.java b/src/com/github/leecho/idea/plugin/mybatis/generator/model/ConnectionConfig.java new file mode 100644 index 0000000..052e3f6 --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/model/ConnectionConfig.java @@ -0,0 +1,77 @@ +package com.github.leecho.idea.plugin.mybatis.generator.model; + +/** + * 数据库链接相关配置 + */ +public class ConnectionConfig { + + private String name; + private String driverClass; + private String url; + private String dataBaseName; + private String dataBaseVersion; + private String schema; + + public ConnectionConfig(String name, String driverClass, String url) { + this.name = name; + this.driverClass = driverClass; + this.url = url; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDriverClass() { + return driverClass; + } + + public void setDriverClass(String driverClass) { + this.driverClass = driverClass; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getDataBaseName() { + return dataBaseName; + } + + public void setDataBaseName(String dataBaseName) { + this.dataBaseName = dataBaseName; + } + + public String getDataBaseVersion() { + return dataBaseVersion; + } + + public void setDataBaseVersion(String dataBaseVersion) { + this.dataBaseVersion = dataBaseVersion; + } + + public boolean isMysql8() { + return this.driverClass.contains("mysql") && dataBaseVersion.startsWith("8."); + } + + public String getSchema() { + return schema; + } + + public void setSchema(String schema) { + // todo 其他类型数据库待处理 + if (this.url.contains("mysql") && !this.url.contains(schema)) { + this.url = this.url + "/" + schema; + } + this.schema = schema; + } + +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/model/Credential.java b/src/com/github/leecho/idea/plugin/mybatis/generator/model/Credential.java index 2691f9c..d7a4c7a 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/model/Credential.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/model/Credential.java @@ -1,24 +1,36 @@ package com.github.leecho.idea.plugin.mybatis.generator.model; /** - * 保存数据库连接对应的用户名,密码存在keepass库中 + * 保存数据库连接对应的用户名&密码 * Created by kangtian on 2018/8/3. */ public class Credential { - //用户名 + //数据链接 + private String url; + //数据库用户名 private String username; + //数据库密码 + private String pwd; public Credential() { } - public Credential(String username) { - this.username = username; - + public Credential(String url) { + this.url = url; } + public Credential(String url, String username) { + this.url = url; + this.username = username; + } + public Credential(String url, String username, String password) { + this.url = url; + this.username = username; + this.pwd = password; + } public String getUsername() { return username; @@ -28,5 +40,19 @@ public void setUsername(String username) { this.username = username; } + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + public String getPwd() { + return pwd; + } + + public void setPwd(String pwd) { + this.pwd = pwd; + } } diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/model/GlobalConfig.java b/src/com/github/leecho/idea/plugin/mybatis/generator/model/GlobalConfig.java index 3e59c8e..ff757be 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/model/GlobalConfig.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/model/GlobalConfig.java @@ -1,320 +1,280 @@ package com.github.leecho.idea.plugin.mybatis.generator.model; +import com.github.leecho.idea.plugin.mybatis.generator.enums.MbgJavaClientConfigTypeEnum; +import com.github.leecho.idea.plugin.mybatis.generator.enums.MbgTargetRuntimeEnum; + public class GlobalConfig { - private String moduleRootPath; - private String sourcePath; - private String resourcePath; - private String mapperPostfix; - private String examplePostfix; - - private String domainPackage; - private String mapperPackage; - private String examplePackage; - private String xmlPackage; - - private String tablePrefix; - - /** - * 是否分页 - */ - private boolean offsetLimit; - - /** - * 是否生成实体注释(来自表) - */ - private boolean comment; - - /** - * 是否覆盖原xml - */ - private boolean override; - - /** - * 是否生成toString/hashCode/equals方法 - */ - private boolean needToStringHashcodeEquals; - - /** - * 是否使用Schema前缀 - */ - private boolean useSchemaPrefix; - - /** - * 是否select 增加ForUpdate - */ - private boolean needForUpdate; - - /** - * 是否DAO使用 @Repository 注解 - */ - private boolean annotationDAO; - - /** - * 是否DAO方法抽出到公共父接口 - */ - private boolean useDAOExtendStyle; - - /** - * 是否JSR310: Date and Time API - */ - private boolean jsr310Support; - - /** - * 是否生成JPA注解 - */ - private boolean annotation; - - /** - * 是否使用实际的列名 - */ - private boolean useActualColumnNames; - - /** - * 是否启用as别名查询 - */ - private boolean useTableNameAlias; - - /** - * 是否使用Example - */ - private boolean useExample; - /** - * 是否是mysql8数据库 - */ - private boolean mysql8; - - private boolean lombokAnnotation; - - private boolean lombokBuilderAnnotation; - - private boolean swaggerAnnotation; - - public String getSourcePath() { - return sourcePath; - } - - public void setSourcePath(String sourcePath) { - this.sourcePath = sourcePath; - } - - public String getResourcePath() { - return resourcePath; - } - - public void setResourcePath(String resourcePath) { - this.resourcePath = resourcePath; - } - - public String getMapperPostfix() { - return mapperPostfix; - } - - public void setMapperPostfix(String mapperPostfix) { - this.mapperPostfix = mapperPostfix; - } - - public String getDomainPackage() { - return domainPackage; - } - - public void setDomainPackage(String domainPackage) { - this.domainPackage = domainPackage; - } - - public String getMapperPackage() { - return mapperPackage; - } - - public void setMapperPackage(String mapperPackage) { - this.mapperPackage = mapperPackage; - } - - public String getXmlPackage() { - return xmlPackage; - } - - public void setXmlPackage(String xmlPackage) { - this.xmlPackage = xmlPackage; - } - - public boolean isOffsetLimit() { - return offsetLimit; - } - - public void setOffsetLimit(boolean offsetLimit) { - this.offsetLimit = offsetLimit; - } - - public boolean isComment() { - return comment; - } + private String sourcePath; + private String resourcePath; + private String defaultXmlPackage; + + private String domainPostfix; + private String mapperPostfix; + private String examplePostfix; + + private String tablePrefix; + + /** + * mybatis generator runtime + * @see MbgTargetRuntimeEnum + */ + private String mgbTargetRuntime; + /** + * mybatis generator java client configuration type + * @see + */ + private String mgbJavaClientConfigType; + + /** + * 是否生成实体注释(来自表) + */ + private boolean comment; + + /** + * 是否覆盖原xml + */ + private boolean override; + + /** + * 是否生成toString/hashCode/equals方法 + */ + private boolean needToStringHashcodeEquals; + + /** + * 是否使用Schema前缀 + */ + private boolean useSchemaPrefix; + + /** + * 是否DAO使用 @Repository 注解 + */ + private boolean annotationDAO; + + /** + * 是否DAO方法抽出到公共父接口 + */ + private boolean useDAOExtendStyle; + + /** + * 是否JSR310: Date and Time API + */ + private boolean jsr310Support; + + /** + * 是否生成JPA注解 + */ + private boolean annotation; + + /** + * 是否使用实际的列名 + */ + private boolean useActualColumnNames; + + /** + * 是否启用as别名查询 + */ + private boolean useTableNameAlias; + + /** + * 是否使用Example + */ + private boolean useExample; + + private boolean lombokAnnotation; + + private boolean lombokBuilderAnnotation; + + + public String getSourcePath() { + return sourcePath; + } + + public void setSourcePath(String sourcePath) { + this.sourcePath = sourcePath; + } + + public String getResourcePath() { + return resourcePath; + } + + public void setResourcePath(String resourcePath) { + this.resourcePath = resourcePath; + } + + public String getMapperPostfix() { + return mapperPostfix; + } + + public void setMapperPostfix(String mapperPostfix) { + this.mapperPostfix = mapperPostfix; + } + + public boolean isComment() { + return comment; + } + + public void setComment(boolean comment) { + this.comment = comment; + } + + public boolean isOverride() { + return override; + } + + public void setOverride(boolean override) { + this.override = override; + } - public void setComment(boolean comment) { - this.comment = comment; - } + public boolean isNeedToStringHashcodeEquals() { + return needToStringHashcodeEquals; + } - public boolean isOverride() { - return override; - } + public void setNeedToStringHashcodeEquals(boolean needToStringHashcodeEquals) { + this.needToStringHashcodeEquals = needToStringHashcodeEquals; + } - public void setOverride(boolean override) { - this.override = override; - } + public boolean isUseSchemaPrefix() { + return useSchemaPrefix; + } - public boolean isNeedToStringHashcodeEquals() { - return needToStringHashcodeEquals; - } + public void setUseSchemaPrefix(boolean useSchemaPrefix) { + this.useSchemaPrefix = useSchemaPrefix; + } - public void setNeedToStringHashcodeEquals(boolean needToStringHashcodeEquals) { - this.needToStringHashcodeEquals = needToStringHashcodeEquals; - } - public boolean isUseSchemaPrefix() { - return useSchemaPrefix; - } + public boolean isAnnotationDAO() { + return annotationDAO; + } - public void setUseSchemaPrefix(boolean useSchemaPrefix) { - this.useSchemaPrefix = useSchemaPrefix; - } + public void setAnnotationDAO(boolean annotationDAO) { + this.annotationDAO = annotationDAO; + } - public boolean isNeedForUpdate() { - return needForUpdate; - } + public boolean isUseDAOExtendStyle() { + return useDAOExtendStyle; + } - public void setNeedForUpdate(boolean needForUpdate) { - this.needForUpdate = needForUpdate; - } + public void setUseDAOExtendStyle(boolean useDAOExtendStyle) { + this.useDAOExtendStyle = useDAOExtendStyle; + } - public boolean isAnnotationDAO() { - return annotationDAO; - } + public boolean isJsr310Support() { + return jsr310Support; + } - public void setAnnotationDAO(boolean annotationDAO) { - this.annotationDAO = annotationDAO; - } + public void setJsr310Support(boolean jsr310Support) { + this.jsr310Support = jsr310Support; + } - public boolean isUseDAOExtendStyle() { - return useDAOExtendStyle; - } + public boolean isAnnotation() { + return annotation; + } - public void setUseDAOExtendStyle(boolean useDAOExtendStyle) { - this.useDAOExtendStyle = useDAOExtendStyle; - } + public void setAnnotation(boolean annotation) { + this.annotation = annotation; + } - public boolean isJsr310Support() { - return jsr310Support; - } + public boolean isUseActualColumnNames() { + return useActualColumnNames; + } - public void setJsr310Support(boolean jsr310Support) { - this.jsr310Support = jsr310Support; - } + public void setUseActualColumnNames(boolean useActualColumnNames) { + this.useActualColumnNames = useActualColumnNames; + } - public boolean isAnnotation() { - return annotation; - } - - public void setAnnotation(boolean annotation) { - this.annotation = annotation; - } - - public boolean isUseActualColumnNames() { - return useActualColumnNames; - } - - public void setUseActualColumnNames(boolean useActualColumnNames) { - this.useActualColumnNames = useActualColumnNames; - } - - public boolean isUseTableNameAlias() { - return useTableNameAlias; - } - - public void setUseTableNameAlias(boolean useTableNameAlias) { - this.useTableNameAlias = useTableNameAlias; - } - - public boolean isUseExample() { - return useExample; - } - - public void setUseExample(boolean useExample) { - this.useExample = useExample; - } - - public boolean isMysql8() { - return mysql8; - } - - public void setMysql8(boolean mysql8) { - this.mysql8 = mysql8; - } - - public boolean isLombokAnnotation() { - return lombokAnnotation; - } - - public void setLombokAnnotation(boolean lombokAnnotation) { - this.lombokAnnotation = lombokAnnotation; - } - - public boolean isLombokBuilderAnnotation() { - return lombokBuilderAnnotation; - } - - public void setLombokBuilderAnnotation(boolean lombokBuilderAnnotation) { - this.lombokBuilderAnnotation = lombokBuilderAnnotation; - } - - public String getModuleRootPath() { - return moduleRootPath; - } - - public void setModuleRootPath(String moduleRootPath) { - this.moduleRootPath = moduleRootPath; - } - - public String getExamplePostfix() { - return examplePostfix; - } - - public void setExamplePostfix(String examplePostfix) { - this.examplePostfix = examplePostfix; - } - - public String getExamplePackage() { - return examplePackage; - } - - public void setExamplePackage(String examplePackage) { - this.examplePackage = examplePackage; - } - - public boolean isSwaggerAnnotation() { - return swaggerAnnotation; - } - - public void setSwaggerAnnotation(boolean swaggerAnnotation) { - this.swaggerAnnotation = swaggerAnnotation; - } - - public String getTablePrefix() { - return tablePrefix; - } - - public void setTablePrefix(String tablePrefix) { - this.tablePrefix = tablePrefix; - } - - public static GlobalConfig getDefault() { - GlobalConfig globalConfig = new GlobalConfig(); - globalConfig.setSourcePath("src/main/java"); - globalConfig.setResourcePath("src/main/resources"); - globalConfig.setMapperPostfix("Mapper"); - globalConfig.setXmlPackage("mapper"); - globalConfig.setExamplePostfix("Example"); - globalConfig.setUseExample(true); - globalConfig.setComment(true); - return globalConfig; - } + public boolean isUseExample() { + return useExample; + } + + public void setUseExample(boolean useExample) { + this.useExample = useExample; + } + + public boolean isLombokAnnotation() { + return lombokAnnotation; + } + + public void setLombokAnnotation(boolean lombokAnnotation) { + this.lombokAnnotation = lombokAnnotation; + } + + public boolean isLombokBuilderAnnotation() { + return lombokBuilderAnnotation; + } + + public void setLombokBuilderAnnotation(boolean lombokBuilderAnnotation) { + this.lombokBuilderAnnotation = lombokBuilderAnnotation; + } + + public String getExamplePostfix() { + return examplePostfix; + } + + public void setExamplePostfix(String examplePostfix) { + this.examplePostfix = examplePostfix; + } + + public String getTablePrefix() { + return tablePrefix; + } + + public void setTablePrefix(String tablePrefix) { + this.tablePrefix = tablePrefix; + } + + public String getDomainPostfix() { + return domainPostfix; + } + + public void setDomainPostfix(String domainPostfix) { + this.domainPostfix = domainPostfix; + } + + public String getDefaultXmlPackage() { + return defaultXmlPackage; + } + + public void setDefaultXmlPackage(String defaultXmlPackage) { + this.defaultXmlPackage = defaultXmlPackage; + } + + public boolean isUseTableNameAlias() { + return useTableNameAlias; + } + + public void setUseTableNameAlias(boolean useTableNameAlias) { + this.useTableNameAlias = useTableNameAlias; + } + + public String getMgbTargetRuntime() { + return mgbTargetRuntime; + } + + public void setMgbTargetRuntime(String mgbTargetRuntime) { + this.mgbTargetRuntime = mgbTargetRuntime; + } + + public String getMgbJavaClientConfigType() { + return mgbJavaClientConfigType; + } + + public void setMgbJavaClientConfigType(String mgbJavaClientConfigType) { + this.mgbJavaClientConfigType = mgbJavaClientConfigType; + } + + public static GlobalConfig getDefault() { + GlobalConfig globalConfig = new GlobalConfig(); + globalConfig.setSourcePath("src/main/java"); + globalConfig.setResourcePath("src/main/resources"); + globalConfig.setDomainPostfix("Entity"); + globalConfig.setMapperPostfix("Mapper"); + globalConfig.setExamplePostfix("Example"); + globalConfig.setUseExample(true); + globalConfig.setComment(true); + globalConfig.setDefaultXmlPackage("mybatis.mapper"); + globalConfig.setMgbTargetRuntime(MbgTargetRuntimeEnum.MY_BATIS3_DYNAMIC_SQL.getName()); + globalConfig.setMgbJavaClientConfigType(MbgJavaClientConfigTypeEnum.MIXEDMAPPER.getName()); + return globalConfig; + } } diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/model/PackageInitialPath.java b/src/com/github/leecho/idea/plugin/mybatis/generator/model/PackageInitialPath.java new file mode 100644 index 0000000..921327c --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/model/PackageInitialPath.java @@ -0,0 +1,54 @@ +package com.github.leecho.idea.plugin.mybatis.generator.model; + +/** + * 各种类型的java包的初始路径 + */ +public class PackageInitialPath { + + private String basePackageInitialPath; + private String domainPackageInitialPath; + private String mapperPackageInitialPath; + private String examplePackageInitialPath; + private String xmlPackageInitialPath; + + public String getBasePackageInitialPath() { + return basePackageInitialPath; + } + + public void setBasePackageInitialPath(String basePackageInitialPath) { + this.basePackageInitialPath = basePackageInitialPath; + } + + public String getDomainPackageInitialPath() { + return domainPackageInitialPath; + } + + public void setDomainPackageInitialPath(String domainPackageInitialPath) { + this.domainPackageInitialPath = domainPackageInitialPath; + } + + public String getMapperPackageInitialPath() { + return mapperPackageInitialPath; + } + + public void setMapperPackageInitialPath(String mapperPackageInitialPath) { + this.mapperPackageInitialPath = mapperPackageInitialPath; + } + + public String getExamplePackageInitialPath() { + return examplePackageInitialPath; + } + + public void setExamplePackageInitialPath(String examplePackageInitialPath) { + this.examplePackageInitialPath = examplePackageInitialPath; + } + + public String getXmlPackageInitialPath() { + return xmlPackageInitialPath; + } + + public void setXmlPackageInitialPath(String xmlPackageInitialPath) { + this.xmlPackageInitialPath = xmlPackageInitialPath; + } + +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/model/TableConfig.java b/src/com/github/leecho/idea/plugin/mybatis/generator/model/TableConfig.java index e6706ff..da669b6 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/model/TableConfig.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/model/TableConfig.java @@ -1,5 +1,6 @@ package com.github.leecho.idea.plugin.mybatis.generator.model; +import com.github.leecho.idea.plugin.mybatis.generator.enums.MbgTargetRuntimeEnum; import java.util.HashMap; import java.util.Map; @@ -8,433 +9,430 @@ */ public class TableConfig { - /** - * 配置名称 - */ - private String name; - - /** - * 表名 - */ - private String tableName; - - /** - * 主键 - */ - private String primaryKey; - - /** - * 实体名 - */ - private String domainName; - - /** - * dao名称 - */ - private String mapperName; - - /** - * dao名称 - */ - private String exampleName; - - /** - * dao后缀 - */ - private String mapperPostfix; - - /** - * dao后缀 - */ - private String examplePostfix; - - /** - * 工程目录 - */ - private String moduleRootPath; - - private String sourcePath; - private String resourcePath; - - private String basePackage; - private String domainPackage; - - private String mapperPackage; - - private String examplePackage; - - private String xmlPackage; - - private Map columnSettings = new HashMap<>(); - /** - * 是否分页 - */ - private boolean offsetLimit; - - /** - * 是否生成实体注释(来自表) - */ - private boolean comment; - - /** - * 是否覆盖原xml - */ - private boolean override; - - /** - * 是否生成toString/hashCode/equals方法 - */ - private boolean needToStringHashcodeEquals; - - /** - * 是否使用Schema前缀 - */ - private boolean useSchemaPrefix; - - /** - * 是否select 增加ForUpdate - */ - private boolean needForUpdate; - - /** - * 是否DAO使用 @Repository 注解 - */ - private boolean annotationDAO; - - /** - * 是否DAO方法抽出到公共父接口 - */ - private boolean useDAOExtendStyle; - - /** - * 是否JSR310: Date and Time API - */ - private boolean jsr310Support; - - /** - * 是否生成JPA注解 - */ - private boolean annotation; - - /** - * 是否使用实际的列名 - */ - private boolean useActualColumnNames; - - /** - * 是否启用as别名查询 - */ - private boolean useTableNameAlias; + /** + * 配置名称 + */ + private String name; + + /** + * 表名 + */ + private String tableName; + + /** + * 主键 + */ + private String primaryKey; + + /** + * 实体名 + */ + private String domainName; + + /** + * mapper名称 + */ + private String mapperName; + + /** + * example名称 + */ + private String exampleName; + + /** + * domain后缀 + */ + private String domainPostfix; + + /** + * dao后缀 + */ + private String mapperPostfix; + + /** + * dao后缀 + */ + private String examplePostfix; + + /** + * 工程目录 + */ + private String moduleRootPath; + + private String sourcePath; + private String resourcePath; + + private String basePackage; + private String domainPackage; + private String mapperPackage; + private String examplePackage; + private String xmlPackage; + /** + * mybatis generator runtime + * @see MbgTargetRuntimeEnum + */ + private String mgbTargetRuntime; + /** + * mybatis generator java client configuration type + * @see + */ + private String mgbJavaClientConfigType; + + private Map columnSettings = new HashMap<>(); + + /** + * 是否生成实体注释(来自表) + */ + private boolean comment; + + /** + * 是否覆盖原xml + */ + private boolean override; + + /** + * 是否生成toString/hashCode/equals方法 + */ + private boolean needToStringHashcodeEquals; + + /** + * 是否使用Schema前缀 + */ + private boolean useSchemaPrefix; + + /** + * 是否DAO使用 @Repository 注解 + */ + private boolean annotationDAO; + + /** + * 是否DAO方法抽出到公共父接口 + */ + private boolean useDAOExtendStyle; + + /** + * 是否JSR310: Date and Time API + */ + private boolean jsr310Support; + + /** + * 是否生成JPA注解 + */ + private boolean annotation; + + /** + * 是否使用实际的列名 + */ + private boolean useActualColumnNames; + /** + * 是否启用as别名查询 + */ + private boolean useTableNameAlias; + /** + * 是否使用Example + */ + private boolean useExample; + /** + * 是否是mysql8数据库 + */ + private boolean mysql8; + + private boolean lombokAnnotation; + + private boolean lombokBuilderAnnotation; + + + private String encoding; + private String connectorJarPath; + + public boolean isJsr310Support() { + return jsr310Support; + } + + public void setJsr310Support(boolean jsr310Support) { + this.jsr310Support = jsr310Support; + } + + public boolean isUseSchemaPrefix() { + return useSchemaPrefix; + } + + public void setUseSchemaPrefix(boolean useSchemaPrefix) { + this.useSchemaPrefix = useSchemaPrefix; + } + + public boolean isUseExample() { + return useExample; + } + + public void setUseExample(boolean useExample) { + this.useExample = useExample; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } - /** - * 是否使用Example - */ - private boolean useExample; - /** - * 是否是mysql8数据库 - */ - private boolean mysql8; + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } - private boolean lombokAnnotation; + public String getDomainName() { + return domainName; + } - private boolean lombokBuilderAnnotation; + public void setDomainName(String domainName) { + this.domainName = domainName; + } - private boolean swaggerAnnotation; + public String getConnectorJarPath() { + return connectorJarPath; + } - private String encoding; - private String connectorJarPath; + public void setConnectorJarPath(String connectorJarPath) { + this.connectorJarPath = connectorJarPath; + } - public boolean isJsr310Support() { - return jsr310Support; - } + public String getModuleRootPath() { + return moduleRootPath; + } - public void setJsr310Support(boolean jsr310Support) { - this.jsr310Support = jsr310Support; - } + public void setModuleRootPath(String moduleRootPath) { + this.moduleRootPath = moduleRootPath; + } - public boolean isUseSchemaPrefix() { - return useSchemaPrefix; - } + public String getDomainPackage() { + return domainPackage; + } - public void setUseSchemaPrefix(boolean useSchemaPrefix) { - this.useSchemaPrefix = useSchemaPrefix; - } + public void setDomainPackage(String domainPackage) { + this.domainPackage = domainPackage; + } - public boolean isUseExample() { - return useExample; - } - - public void setUseExample(boolean useExample) { - this.useExample = useExample; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - public String getTableName() { - return tableName; - } + public String getMapperPackage() { + return mapperPackage; + } - public void setTableName(String tableName) { - this.tableName = tableName; - } + public void setMapperPackage(String mapperPackage) { + this.mapperPackage = mapperPackage; + } - public String getDomainName() { - return domainName; - } - public void setDomainName(String domainName) { - this.domainName = domainName; - } + public String getXmlPackage() { + return xmlPackage; + } - public String getConnectorJarPath() { - return connectorJarPath; - } + public void setXmlPackage(String xmlPackage) { + this.xmlPackage = xmlPackage; + } - public void setConnectorJarPath(String connectorJarPath) { - this.connectorJarPath = connectorJarPath; - } + public boolean isComment() { + return comment; + } - public String getModuleRootPath() { - return moduleRootPath; - } + public void setComment(boolean comment) { + this.comment = comment; + } - public void setModuleRootPath(String moduleRootPath) { - this.moduleRootPath = moduleRootPath; - } + public boolean isNeedToStringHashcodeEquals() { + return needToStringHashcodeEquals; + } - public String getDomainPackage() { - return domainPackage; - } + public void setNeedToStringHashcodeEquals(boolean needToStringHashcodeEquals) { + this.needToStringHashcodeEquals = needToStringHashcodeEquals; + } - public void setDomainPackage(String domainPackage) { - this.domainPackage = domainPackage; - } + public boolean isAnnotationDAO() { + return annotationDAO; + } - public String getMapperPackage() { - return mapperPackage; - } + public void setAnnotationDAO(boolean annotationDAO) { + this.annotationDAO = annotationDAO; + } - public void setMapperPackage(String mapperPackage) { - this.mapperPackage = mapperPackage; - } + public boolean isAnnotation() { + return annotation; + } + public void setAnnotation(boolean annotation) { + this.annotation = annotation; + } - public String getXmlPackage() { - return xmlPackage; - } + public boolean isUseActualColumnNames() { + return useActualColumnNames; + } - public void setXmlPackage(String xmlPackage) { - this.xmlPackage = xmlPackage; - } + public void setUseActualColumnNames(boolean useActualColumnNames) { + this.useActualColumnNames = useActualColumnNames; + } - public boolean isOffsetLimit() { - return offsetLimit; - } + public String getMapperName() { + return mapperName; + } - public void setOffsetLimit(boolean offsetLimit) { - this.offsetLimit = offsetLimit; - } + public void setMapperName(String mapperName) { + this.mapperName = mapperName; + } - public boolean isComment() { - return comment; - } + public String getPrimaryKey() { + return primaryKey; + } - public void setComment(boolean comment) { - this.comment = comment; - } + public void setPrimaryKey(String primaryKey) { + this.primaryKey = primaryKey; + } - public boolean isNeedToStringHashcodeEquals() { - return needToStringHashcodeEquals; - } + public String getEncoding() { + return encoding; + } - public void setNeedToStringHashcodeEquals(boolean needToStringHashcodeEquals) { - this.needToStringHashcodeEquals = needToStringHashcodeEquals; - } + public void setEncoding(String encoding) { + this.encoding = encoding; + } - public boolean isNeedForUpdate() { - return needForUpdate; - } + public boolean isOverride() { + return override; + } - public void setNeedForUpdate(boolean needForUpdate) { - this.needForUpdate = needForUpdate; - } + public void setOverride(boolean override) { + this.override = override; + } - public boolean isAnnotationDAO() { - return annotationDAO; - } + public void setUseDAOExtendStyle(boolean useDAOExtendStyle) { + this.useDAOExtendStyle = useDAOExtendStyle; + } - public void setAnnotationDAO(boolean annotationDAO) { - this.annotationDAO = annotationDAO; - } + public boolean isUseDAOExtendStyle() { + return useDAOExtendStyle; + } - public boolean isAnnotation() { - return annotation; - } + public String getSourcePath() { + return sourcePath; + } - public void setAnnotation(boolean annotation) { - this.annotation = annotation; - } + public void setSourcePath(String sourcePath) { + this.sourcePath = sourcePath; + } - public boolean isUseActualColumnNames() { - return useActualColumnNames; - } + public String getResourcePath() { + return resourcePath; + } - public void setUseActualColumnNames(boolean useActualColumnNames) { - this.useActualColumnNames = useActualColumnNames; - } + public void setResourcePath(String resourcePath) { + this.resourcePath = resourcePath; + } - public String getMapperName() { - return mapperName; - } + public String getMapperPostfix() { + return mapperPostfix; + } - public void setMapperName(String mapperName) { - this.mapperName = mapperName; - } + public void setMapperPostfix(String mapperPostfix) { + this.mapperPostfix = mapperPostfix; + } - public String getPrimaryKey() { - return primaryKey; - } + public boolean isMysql8() { + return mysql8; + } - public void setPrimaryKey(String primaryKey) { - this.primaryKey = primaryKey; - } + public void setMysql8(boolean mysql8) { + this.mysql8 = mysql8; + } - public String getEncoding() { - return encoding; - } + public boolean isLombokAnnotation() { + return lombokAnnotation; + } - public void setEncoding(String encoding) { - this.encoding = encoding; - } + public void setLombokAnnotation(boolean lombokAnnotation) { + this.lombokAnnotation = lombokAnnotation; + } - public boolean getUseTableNameAlias() { - return useTableNameAlias; - } + public boolean isLombokBuilderAnnotation() { + return lombokBuilderAnnotation; + } - public void setUseTableNameAlias(boolean useTableNameAlias) { - this.useTableNameAlias = useTableNameAlias; - } + public void setLombokBuilderAnnotation(boolean lombokBuilderAnnotation) { + this.lombokBuilderAnnotation = lombokBuilderAnnotation; + } - public boolean isUseTableNameAlias() { - return useTableNameAlias; - } + public String getExamplePackage() { + return examplePackage; + } - public boolean isOverride() { - return override; - } + public void setExamplePackage(String examplePackage) { + this.examplePackage = examplePackage; + } - public void setOverride(boolean override) { - this.override = override; - } + public String getExamplePostfix() { + return examplePostfix; + } - public void setUseDAOExtendStyle(boolean useDAOExtendStyle) { - this.useDAOExtendStyle = useDAOExtendStyle; - } + public void setExamplePostfix(String examplePostfix) { + this.examplePostfix = examplePostfix; + } - public boolean isUseDAOExtendStyle() { - return useDAOExtendStyle; - } + public String getExampleName() { + return exampleName; + } - public String getSourcePath() { - return sourcePath; - } + public void setExampleName(String exampleName) { + this.exampleName = exampleName; + } - public void setSourcePath(String sourcePath) { - this.sourcePath = sourcePath; - } + public String getBasePackage() { + return basePackage; + } - public String getResourcePath() { - return resourcePath; - } + public void setBasePackage(String basePackage) { + this.basePackage = basePackage; + } - public void setResourcePath(String resourcePath) { - this.resourcePath = resourcePath; - } + public Map getColumnSettings() { + return columnSettings; + } - public String getMapperPostfix() { - return mapperPostfix; - } + public void setColumnSettings(Map columnSettings) { + this.columnSettings = columnSettings; + } - public void setMapperPostfix(String mapperPostfix) { - this.mapperPostfix = mapperPostfix; - } + public String getDomainPostfix() { + return domainPostfix; + } - public boolean isMysql8() { - return mysql8; - } + public void setDomainPostfix(String domainPostfix) { + this.domainPostfix = domainPostfix; + } - public void setMysql8(boolean mysql8) { - this.mysql8 = mysql8; - } + public String getMgbTargetRuntime() { + return mgbTargetRuntime; + } - public boolean isLombokAnnotation() { - return lombokAnnotation; - } + public void setMgbTargetRuntime(String mgbTargetRuntime) { + this.mgbTargetRuntime = mgbTargetRuntime; + } - public void setLombokAnnotation(boolean lombokAnnotation) { - this.lombokAnnotation = lombokAnnotation; - } + public boolean isUseTableNameAlias() { + return useTableNameAlias; + } - public boolean isLombokBuilderAnnotation() { - return lombokBuilderAnnotation; - } + public void setUseTableNameAlias(boolean useTableNameAlias) { + this.useTableNameAlias = useTableNameAlias; + } - public void setLombokBuilderAnnotation(boolean lombokBuilderAnnotation) { - this.lombokBuilderAnnotation = lombokBuilderAnnotation; - } + public String getMgbJavaClientConfigType() { + return mgbJavaClientConfigType; + } - public boolean isSwaggerAnnotation() { - return swaggerAnnotation; - } - - public void setSwaggerAnnotation(boolean swaggerAnnotation) { - this.swaggerAnnotation = swaggerAnnotation; - } - - public String getExamplePackage() { - return examplePackage; - } - - public void setExamplePackage(String examplePackage) { - this.examplePackage = examplePackage; - } - - public String getExamplePostfix() { - return examplePostfix; - } - - public void setExamplePostfix(String examplePostfix) { - this.examplePostfix = examplePostfix; - } - - public String getExampleName() { - return exampleName; - } - - public void setExampleName(String exampleName) { - this.exampleName = exampleName; - } - - public String getBasePackage() { - return basePackage; - } - - public void setBasePackage(String basePackage) { - this.basePackage = basePackage; - } - - public Map getColumnSettings() { - return columnSettings; - } - - public void setColumnSettings(Map columnSettings) { - this.columnSettings = columnSettings; - } + public void setMgbJavaClientConfigType(String mgbJavaClientConfigType) { + this.mgbJavaClientConfigType = mgbJavaClientConfigType; + } } diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/CommonDAOInterfacePlugin.java b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/CommonDAOInterfacePlugin.java new file mode 100644 index 0000000..998724c --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/CommonDAOInterfacePlugin.java @@ -0,0 +1,249 @@ +package com.github.leecho.idea.plugin.mybatis.generator.plugin; + +import java.io.File; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import org.mybatis.generator.api.GeneratedJavaFile; +import org.mybatis.generator.api.IntrospectedColumn; +import org.mybatis.generator.api.IntrospectedTable; +import org.mybatis.generator.api.JavaFormatter; +import org.mybatis.generator.api.PluginAdapter; +import org.mybatis.generator.api.ShellCallback; +import org.mybatis.generator.api.dom.java.CompilationUnit; +import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; +import org.mybatis.generator.api.dom.java.Interface; +import org.mybatis.generator.api.dom.java.JavaVisibility; +import org.mybatis.generator.api.dom.java.Method; +import org.mybatis.generator.api.dom.java.Parameter; +import org.mybatis.generator.api.dom.java.TopLevelClass; +import org.mybatis.generator.exception.ShellException; +import org.mybatis.generator.internal.DefaultShellCallback; +import org.mybatis.generator.internal.util.StringUtility; + +public class CommonDAOInterfacePlugin extends PluginAdapter { + private static final String DEFAULT_DAO_SUPER_CLASS = ".MyBatisBaseDao"; + private static final FullyQualifiedJavaType PARAM_ANNOTATION_TYPE = new FullyQualifiedJavaType("org.apache.ibatis.annotations.Param"); + private static final FullyQualifiedJavaType LIST_TYPE = FullyQualifiedJavaType.getNewListInstance(); + private static final FullyQualifiedJavaType SERIALIZEBLE_TYPE = new FullyQualifiedJavaType("java.io.Serializable"); + private List methods = new ArrayList(); + private ShellCallback shellCallback = null; + + public CommonDAOInterfacePlugin() { + this.shellCallback = new DefaultShellCallback(false); + } + + public List contextGenerateAdditionalJavaFiles( + IntrospectedTable introspectedTable) { + boolean hasPk = introspectedTable.hasPrimaryKeyColumns(); + JavaFormatter javaFormatter = this.context.getJavaFormatter(); + String daoTargetDir = this.context.getJavaClientGeneratorConfiguration().getTargetProject(); + String daoTargetPackage = this.context.getJavaClientGeneratorConfiguration().getTargetPackage(); + List mapperJavaFiles = new ArrayList(); + String javaFileEncoding = this.context.getProperty("javaFileEncoding"); + Interface mapperInterface = new Interface(daoTargetPackage + ".MyBatisBaseDao"); + if (StringUtility.stringHasValue(daoTargetPackage)) { + mapperInterface.addImportedType(PARAM_ANNOTATION_TYPE); + mapperInterface.addImportedType(LIST_TYPE); + mapperInterface.addImportedType(SERIALIZEBLE_TYPE); + mapperInterface.setVisibility(JavaVisibility.PUBLIC); + mapperInterface.addJavaDocLine("/**"); + mapperInterface.addJavaDocLine(" * DAO公共基类,由MybatisGenerator自动生成请勿修改"); + mapperInterface.addJavaDocLine(" * @param The Model Class 这里是泛型不是Model类"); + mapperInterface.addJavaDocLine(" * @param The Primary Key Class 如果是无主键,则可以用Model来跳过,如果是多主键则是Key类"); + mapperInterface.addJavaDocLine(" * @param The Example Class"); + mapperInterface.addJavaDocLine(" */"); + FullyQualifiedJavaType daoBaseInterfaceJavaType = mapperInterface.getType(); + daoBaseInterfaceJavaType.addTypeArgument(new FullyQualifiedJavaType("Model")); + daoBaseInterfaceJavaType.addTypeArgument(new FullyQualifiedJavaType("PK extends Serializable")); + daoBaseInterfaceJavaType.addTypeArgument(new FullyQualifiedJavaType("E")); + if (!this.methods.isEmpty()) { + Iterator var10 = this.methods.iterator(); + + while(var10.hasNext()) { + Method method = (Method)var10.next(); + mapperInterface.addMethod(method); + } + } + + List generatedJavaFiles = introspectedTable.getGeneratedJavaFiles(); + Iterator var18 = generatedJavaFiles.iterator(); + + while(var18.hasNext()) { + GeneratedJavaFile generatedJavaFile = (GeneratedJavaFile)var18.next(); + CompilationUnit compilationUnit = generatedJavaFile.getCompilationUnit(); + FullyQualifiedJavaType type = compilationUnit.getType(); + String modelName = type.getShortName(); + if (modelName.endsWith("DAO")) { + } + } + + GeneratedJavaFile mapperJavafile = new GeneratedJavaFile(mapperInterface, daoTargetDir, javaFileEncoding, javaFormatter); + + try { + File mapperDir = this.shellCallback.getDirectory(daoTargetDir, daoTargetPackage); + File mapperFile = new File(mapperDir, mapperJavafile.getFileName()); + if (!mapperFile.exists()) { + mapperJavaFiles.add(mapperJavafile); + } + } catch (ShellException var16) { + var16.printStackTrace(); + } + } + + return mapperJavaFiles; + } + + public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { + interfaze.addJavaDocLine("/**"); + interfaze.addJavaDocLine(" * " + interfaze.getType().getShortName() + "继承基类"); + interfaze.addJavaDocLine(" */"); + String daoSuperClass = interfaze.getType().getPackageName() + ".MyBatisBaseDao"; + FullyQualifiedJavaType daoSuperType = new FullyQualifiedJavaType(daoSuperClass); + String targetPackage = introspectedTable.getContext().getJavaModelGeneratorConfiguration().getTargetPackage(); + String domainObjectName = introspectedTable.getTableConfiguration().getDomainObjectName(); + FullyQualifiedJavaType baseModelJavaType = new FullyQualifiedJavaType(targetPackage + "." + domainObjectName); + daoSuperType.addTypeArgument(baseModelJavaType); + FullyQualifiedJavaType primaryKeyTypeJavaType = null; + if (introspectedTable.getPrimaryKeyColumns().size() > 1) { + primaryKeyTypeJavaType = new FullyQualifiedJavaType(targetPackage + "." + domainObjectName + "Key"); + } else if (introspectedTable.hasPrimaryKeyColumns()) { + primaryKeyTypeJavaType = ((IntrospectedColumn)introspectedTable.getPrimaryKeyColumns().get(0)).getFullyQualifiedJavaType(); + } else { + primaryKeyTypeJavaType = baseModelJavaType; + } + + daoSuperType.addTypeArgument(primaryKeyTypeJavaType); + String exampleType = introspectedTable.getExampleType(); + FullyQualifiedJavaType exampleTypeJavaType = new FullyQualifiedJavaType(exampleType); + daoSuperType.addTypeArgument(exampleTypeJavaType); + interfaze.addImportedType(primaryKeyTypeJavaType); + interfaze.addImportedType(exampleTypeJavaType); + interfaze.addImportedType(baseModelJavaType); + interfaze.addImportedType(daoSuperType); + interfaze.addSuperInterface(daoSuperType); + return true; + } + + public boolean validate(List list) { + return true; + } + + private void interceptExampleParam(Method method) { + method.getParameters().clear(); + method.addParameter(new Parameter(new FullyQualifiedJavaType("E"), "example")); + this.methods.add(method); + } + + private void interceptPrimaryKeyParam(Method method) { + method.getParameters().clear(); + method.addParameter(new Parameter(new FullyQualifiedJavaType("PK"), "id")); + this.methods.add(method); + } + + private void interceptModelParam(Method method) { + method.getParameters().clear(); + method.addParameter(new Parameter(new FullyQualifiedJavaType("Model"), "record")); + this.methods.add(method); + } + + private void interceptModelAndExampleParam(Method method) { + List parameters = method.getParameters(); + if (parameters.size() == 1) { + this.interceptExampleParam(method); + } else { + method.getParameters().clear(); + Parameter parameter1 = new Parameter(new FullyQualifiedJavaType("Model"), "record"); + parameter1.addAnnotation("@Param(\"record\")"); + method.addParameter(parameter1); + Parameter parameter2 = new Parameter(new FullyQualifiedJavaType("E"), "example"); + parameter2.addAnnotation("@Param(\"example\")"); + method.addParameter(parameter2); + this.methods.add(method); + } + + } + + public boolean clientCountByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptExampleParam(method); + return false; + } + + public boolean clientDeleteByExampleMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptExampleParam(method); + return false; + } + + public boolean clientDeleteByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptPrimaryKeyParam(method); + return false; + } + + public boolean clientInsertMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptModelParam(method); + return false; + } + + public boolean clientSelectByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptExampleParam(method); + method.setReturnType(new FullyQualifiedJavaType("List")); + return false; + } + + public boolean clientSelectByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptExampleParam(method); + method.setReturnType(new FullyQualifiedJavaType("List")); + return false; + } + + public boolean clientSelectByPrimaryKeyMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptPrimaryKeyParam(method); + method.setReturnType(new FullyQualifiedJavaType("Model")); + return false; + } + + public boolean clientUpdateByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptModelAndExampleParam(method); + return false; + } + + public boolean clientUpdateByExampleWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptModelAndExampleParam(method); + return false; + } + + public boolean clientUpdateByExampleWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptModelAndExampleParam(method); + return false; + } + + public boolean clientUpdateByPrimaryKeySelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptModelParam(method); + return false; + } + + public boolean clientUpdateByExampleWithoutBLOBsMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { + this.interceptModelAndExampleParam(method); + return false; + } + + public boolean clientUpdateByExampleSelectiveMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { + this.interceptModelAndExampleParam(method); + return false; + } + + public boolean clientUpdateByPrimaryKeyWithBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptModelParam(method); + return false; + } + + public boolean clientUpdateByPrimaryKeyWithoutBLOBsMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptModelParam(method); + return false; + } + + public boolean clientInsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) { + this.interceptModelParam(method); + return false; + } +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/DbRemarksCommentGenerator.java b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/DbRemarksCommentGenerator.java new file mode 100644 index 0000000..1b0d060 --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/DbRemarksCommentGenerator.java @@ -0,0 +1,140 @@ +package com.github.leecho.idea.plugin.mybatis.generator.plugin; + +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; +import org.mybatis.generator.api.CommentGenerator; +import org.mybatis.generator.api.IntrospectedColumn; +import org.mybatis.generator.api.IntrospectedTable; +import org.mybatis.generator.api.dom.java.CompilationUnit; +import org.mybatis.generator.api.dom.java.Field; +import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; +import org.mybatis.generator.api.dom.java.InnerClass; +import org.mybatis.generator.api.dom.java.InnerEnum; +import org.mybatis.generator.api.dom.java.Method; +import org.mybatis.generator.api.dom.java.TopLevelClass; +import org.mybatis.generator.api.dom.xml.XmlElement; +import org.mybatis.generator.internal.util.StringUtility; + +public class DbRemarksCommentGenerator implements CommentGenerator { + private Properties properties = new Properties(); + private boolean columnRemarks; + private boolean isAnnotations; + + public DbRemarksCommentGenerator() { + } + + public void addJavaFileComment(CompilationUnit compilationUnit) { + if (this.isAnnotations) { + compilationUnit.addImportedType(new FullyQualifiedJavaType("javax.persistence.Table")); + compilationUnit.addImportedType(new FullyQualifiedJavaType("javax.persistence.Id")); + compilationUnit.addImportedType(new FullyQualifiedJavaType("javax.persistence.Column")); + compilationUnit.addImportedType(new FullyQualifiedJavaType("javax.persistence.GeneratedValue")); + compilationUnit.addImportedType(new FullyQualifiedJavaType("org.hibernate.validator.constraints.NotEmpty")); + } + + } + + public void addComment(XmlElement xmlElement) { + } + + public void addRootComment(XmlElement rootElement) { + } + + public void addGeneralMethodAnnotation( + Method method, IntrospectedTable introspectedTable, Set imports) { + } + + public void addGeneralMethodAnnotation(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set imports) { + } + + public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, Set imports) { + } + + public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set imports) { + } + + public void addClassAnnotation(InnerClass innerClass, IntrospectedTable introspectedTable, Set imports) { + } + + public void addConfigurationProperties(Properties properties) { + this.properties.putAll(properties); + this.columnRemarks = StringUtility.isTrue(properties.getProperty("columnRemarks")); + this.isAnnotations = StringUtility.isTrue(properties.getProperty("annotations")); + } + + public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) { + } + + public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { + topLevelClass.addJavaDocLine("/**"); + topLevelClass.addJavaDocLine(" * " + introspectedTable.getFullyQualifiedTable().getIntrospectedTableName()); + topLevelClass.addJavaDocLine(" * @author "); + topLevelClass.addJavaDocLine(" */"); + if (this.isAnnotations) { + topLevelClass.addAnnotation("@Table(name=\"" + introspectedTable.getFullyQualifiedTableNameAtRuntime() + "\")"); + } + + } + + public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) { + } + + public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { + if (StringUtility.stringHasValue(introspectedColumn.getRemarks())) { + field.addJavaDocLine("/**"); + StringBuilder sb = new StringBuilder(); + sb.append(" * "); + sb.append(introspectedColumn.getRemarks()); + field.addJavaDocLine(sb.toString()); + field.addJavaDocLine(" */"); + } + + if (this.isAnnotations) { + boolean isId = false; + Iterator var5 = introspectedTable.getPrimaryKeyColumns().iterator(); + + while(var5.hasNext()) { + IntrospectedColumn column = (IntrospectedColumn)var5.next(); + if (introspectedColumn == column) { + isId = true; + field.addAnnotation("@Id"); + field.addAnnotation("@GeneratedValue"); + break; + } + } + + if (!introspectedColumn.isNullable() && !isId) { + field.addAnnotation("@NotEmpty"); + } + + if (introspectedColumn.isIdentity()) { + if (introspectedTable.getTableConfiguration().getGeneratedKey().getRuntimeSqlStatement().equals("JDBC")) { + field.addAnnotation("@GeneratedValue(generator = \"JDBC\")"); + } else { + field.addAnnotation("@GeneratedValue(strategy = GenerationType.IDENTITY)"); + } + } else if (introspectedColumn.isSequenceColumn()) { + field.addAnnotation("@SequenceGenerator(name=\"\",sequenceName=\"" + introspectedTable.getTableConfiguration().getGeneratedKey().getRuntimeSqlStatement() + "\")"); + } + } + + } + + public void addFieldComment(Field field, IntrospectedTable introspectedTable) { + } + + public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) { + } + + public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { + } + + public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) { + } + + public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) { + innerClass.addJavaDocLine("/**"); + innerClass.addJavaDocLine(" */"); + } +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/LombokPlugin.java b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/LombokPlugin.java index f7dccb4..407fe9d 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/LombokPlugin.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/LombokPlugin.java @@ -184,7 +184,6 @@ public void setProperties(Properties properties) { } } - @Override public boolean clientGenerated( Interface interfaze, TopLevelClass topLevelClass, diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/MyJavaTypeResolverDefaultImpl.java b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/MyJavaTypeResolverDefaultImpl.java new file mode 100644 index 0000000..83b5aee --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/MyJavaTypeResolverDefaultImpl.java @@ -0,0 +1,40 @@ +package com.github.leecho.idea.plugin.mybatis.generator.plugin; + +import java.sql.Types; +import org.mybatis.generator.api.IntrospectedColumn; +import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; +import org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl; + +public class MyJavaTypeResolverDefaultImpl extends JavaTypeResolverDefaultImpl { + + @Override + protected FullyQualifiedJavaType overrideDefaultType(IntrospectedColumn column, + FullyQualifiedJavaType defaultType) { + FullyQualifiedJavaType answer = defaultType; + + switch (column.getJdbcType()) { + case Types.BIT: + answer = calculateBitReplacement(column, defaultType); + break; + case Types.DATE: + answer = calculateDateType(column, defaultType); + break; + case Types.DECIMAL: + case Types.NUMERIC: + answer = calculateBigDecimalReplacement(column, defaultType); + break; + case Types.TIME: + answer = calculateTimeType(column, defaultType); + break; + case Types.TIMESTAMP: + answer = calculateTimestampType(column, defaultType); + break; + case Types.TINYINT: + answer = new FullyQualifiedJavaType("java.lang.Integer"); + default: + break; + } + + return answer; + } +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/RepositoryPlugin.java b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/RepositoryPlugin.java new file mode 100644 index 0000000..93b1004 --- /dev/null +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/RepositoryPlugin.java @@ -0,0 +1,27 @@ +package com.github.leecho.idea.plugin.mybatis.generator.plugin; + +import java.util.List; +import org.mybatis.generator.api.IntrospectedTable; +import org.mybatis.generator.api.PluginAdapter; +import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; +import org.mybatis.generator.api.dom.java.Interface; +import org.mybatis.generator.api.dom.java.TopLevelClass; + +public class RepositoryPlugin extends PluginAdapter { + private FullyQualifiedJavaType annotationRepository = new FullyQualifiedJavaType("org.springframework.stereotype.Repository"); + private String annotation = "@Repository"; + + public RepositoryPlugin() { + } + + public boolean validate(List list) { + return true; + } + + public boolean clientGenerated( + Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) { + interfaze.addImportedType(this.annotationRepository); + interfaze.addAnnotation(this.annotation); + return true; + } +} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/SwaggerPlugin.java b/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/SwaggerPlugin.java deleted file mode 100644 index da2f10b..0000000 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/plugin/SwaggerPlugin.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.github.leecho.idea.plugin.mybatis.generator.plugin; - -import com.github.leecho.idea.plugin.mybatis.generator.util.StringUtils; -import org.mybatis.generator.api.IntrospectedColumn; -import org.mybatis.generator.api.IntrospectedTable; -import org.mybatis.generator.api.PluginAdapter; -import org.mybatis.generator.api.dom.java.Field; -import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; -import org.mybatis.generator.api.dom.java.Interface; -import org.mybatis.generator.api.dom.java.TopLevelClass; - -import java.util.List; - - -/** - * A MyBatis Generator plugin to use Lombok's annotations. - * For example, use @Data annotation instead of getter ands setter. - * - * @author Paolo Predonzani (http://softwareloop.com/) - */ -public class SwaggerPlugin extends PluginAdapter { - - /** - * @param warnings list of warnings - * @return always true - */ - @Override - public boolean validate(List warnings) { - return true; - } - - /** - * Intercepts base record class generation - * - * @param topLevelClass the generated base record class - * @param introspectedTable The class containing information about the table as - * introspected from the database - * @return always true - */ - @Override - public boolean modelBaseRecordClassGenerated( - TopLevelClass topLevelClass, - IntrospectedTable introspectedTable - ) { - addAnnotations(topLevelClass, introspectedTable.getRemarks()); - return true; - } - - /** - * Intercepts primary key class generation - * - * @param topLevelClass the generated primary key class - * @param introspectedTable The class containing information about the table as - * introspected from the database - * @return always true - */ - @Override - public boolean modelPrimaryKeyClassGenerated( - TopLevelClass topLevelClass, - IntrospectedTable introspectedTable - ) { - addAnnotations(topLevelClass, introspectedTable.getRemarks()); - return true; - } - - /** - * Intercepts "record with blob" class generation - * - * @param topLevelClass the generated record with BLOBs class - * @param introspectedTable The class containing information about the table as - * introspected from the database - * @return always true - */ - @Override - public boolean modelRecordWithBLOBsClassGenerated( - TopLevelClass topLevelClass, - IntrospectedTable introspectedTable - ) { - addAnnotations(topLevelClass, introspectedTable.getRemarks()); - return true; - } - - @Override - public boolean modelFieldGenerated(Field field, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) { - if (!StringUtils.isEmpty(introspectedColumn.getRemarks())) { - addFieldAnnotations(topLevelClass, field, introspectedColumn.getRemarks()); - } - return true; - } - - /** - * Adds the lombok annotations' imports and annotations to the class - * - * @param topLevelClass the partially implemented model class - */ - private void addFieldAnnotations(TopLevelClass topLevelClass, Field field, String name) { - topLevelClass.addImportedType(new FullyQualifiedJavaType("io.swagger.annotations.ApiModelProperty")); - field.addAnnotation(String.format("@ApiModelProperty(\"%s\")", name)); - } - - /** - * Adds the lombok annotations' imports and annotations to the class - * - * @param topLevelClass the partially implemented model class - */ - private void addAnnotations(TopLevelClass topLevelClass, String name) { - topLevelClass.addImportedType(new FullyQualifiedJavaType("io.swagger.annotations.ApiModel")); - String[] parts = name.split("\\."); - topLevelClass.addAnnotation(String.format("@ApiModel(\"%s\")", parts[parts.length - 1])); - } - - - @Override - public boolean clientGenerated( - Interface interfaze, - TopLevelClass topLevelClass, - IntrospectedTable introspectedTable - ) { - interfaze.addImportedType(new FullyQualifiedJavaType( - "org.apache.ibatis.annotations.Mapper")); - interfaze.addAnnotation("@Mapper"); - return true; - } -} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/setting/MyBatisGeneratorConfiguration.java b/src/com/github/leecho/idea/plugin/mybatis/generator/setting/MyBatisGeneratorConfiguration.java index 2d0bb2e..897354e 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/setting/MyBatisGeneratorConfiguration.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/setting/MyBatisGeneratorConfiguration.java @@ -2,6 +2,7 @@ import com.github.leecho.idea.plugin.mybatis.generator.model.TableConfig; import com.github.leecho.idea.plugin.mybatis.generator.model.Credential; +import com.intellij.openapi.components.ComponentManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.components.State; @@ -26,7 +27,7 @@ public class MyBatisGeneratorConfiguration implements PersistentStateComponent(); private JTextField usernameField = new JBTextField(30); private JTextField passwordField = new JBPasswordField(); private JLabel errorMessage = new JLabel(""); + private Credential credential; - public DatabaseCredentialUI(Project project, String url) throws HeadlessException { + public DatabaseCredentialUI(Project project, Credential credential) throws HeadlessException { super(project); - this.url = url; - this.project = project; - this.myBatisGeneratorConfiguration = MyBatisGeneratorConfiguration.getInstance(project); + this.credential = credential; setTitle("Connect to Database"); pack(); contentPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); - Map credentials = myBatisGeneratorConfiguration.getCredentials(); - JPanel usernamePanel = new JBPanel<>(); usernamePanel.setLayout(new BoxLayout(usernamePanel, BoxLayout.X_AXIS)); usernamePanel.setBorder(JBUI.Borders.empty(1)); JLabel usernameLabel = new JLabel("Username:"); - usernameLabel.setPreferredSize(new Dimension(80, 20)); usernamePanel.add(usernameLabel); usernamePanel.add(usernameField); - if(credentials != null && credentials.containsKey(url)){ - usernameField.setText(credentials.get(url).getUsername()); - } + contentPanel.add(usernamePanel); JPanel passwordPanel = new JBPanel<>(); passwordPanel.setLayout(new BoxLayout(passwordPanel, BoxLayout.X_AXIS)); passwordPanel.setBorder(JBUI.Borders.empty(1)); JLabel passwordLabel = new JLabel("Password:"); - passwordLabel.setPreferredSize(new Dimension(80, 20)); passwordPanel.add(passwordLabel); passwordPanel.add(passwordField); - contentPanel.add(usernamePanel); contentPanel.add(passwordPanel); contentPanel.add(errorMessage); errorMessage.setForeground(JBColor.RED); @@ -87,19 +68,8 @@ protected void doOKAction() { errorMessage.setText("Password must not be null"); return; } - - Map credentials = myBatisGeneratorConfiguration.getCredentials(); - if (credentials == null) { - credentials = new HashMap<>(); - } - credentials.put(url, new Credential(usernameField.getText())); - CredentialAttributes attributes = new CredentialAttributes(PluginContants.PLUGIN_NAME + "-" + url, usernameField.getText(), this.getClass(), false); - Credentials saveCredentials = new Credentials(attributes.getUserName(), passwordField.getText()); - PasswordSafe.getInstance().set(attributes, saveCredentials); - myBatisGeneratorConfiguration.setCredentials(credentials); - VirtualFile baseDir = project.getBaseDir(); - baseDir.refresh(false, true); - + credential.setUsername(usernameField.getText().trim()); + credential.setPwd(passwordField.getText().trim()); super.doOKAction(); } diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/ui/GenerateSettingUI.java b/src/com/github/leecho/idea/plugin/mybatis/generator/ui/GenerateSettingUI.java index 13314ed..09da4b9 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/ui/GenerateSettingUI.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/ui/GenerateSettingUI.java @@ -1,7 +1,10 @@ package com.github.leecho.idea.plugin.mybatis.generator.ui; -import com.github.leecho.idea.plugin.mybatis.generator.contants.PluginContants; +import com.github.leecho.idea.plugin.mybatis.generator.enums.MbgJavaClientConfigTypeEnum; +import com.github.leecho.idea.plugin.mybatis.generator.enums.MbgTargetRuntimeEnum; +import com.github.leecho.idea.plugin.mybatis.generator.enums.PackageTypeEnum; import com.github.leecho.idea.plugin.mybatis.generator.generate.MyBatisGenerateCommand; +import com.github.leecho.idea.plugin.mybatis.generator.model.ConnectionConfig; import com.github.leecho.idea.plugin.mybatis.generator.model.Credential; import com.github.leecho.idea.plugin.mybatis.generator.model.GlobalConfig; import com.github.leecho.idea.plugin.mybatis.generator.model.TableConfig; @@ -10,12 +13,11 @@ import com.github.leecho.idea.plugin.mybatis.generator.util.DatabaseUtils; import com.github.leecho.idea.plugin.mybatis.generator.util.JTextFieldHintListener; import com.github.leecho.idea.plugin.mybatis.generator.util.StringUtils; -import com.intellij.credentialStore.CredentialAttributes; +import com.intellij.database.model.NameVersion; import com.intellij.database.model.RawConnectionConfig; import com.intellij.database.psi.DbDataSource; +import com.intellij.database.psi.DbNamespace; import com.intellij.database.psi.DbTable; -import com.intellij.ide.passwordSafe.PasswordSafe; -import com.intellij.ide.util.PackageChooserDialog; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.actionSystem.PlatformDataKeys; @@ -23,15 +25,22 @@ import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.*; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; -import com.intellij.psi.PsiPackage; -import com.intellij.ui.EditorTextFieldWithBrowseButton; import com.intellij.ui.TitledSeparator; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBPanel; import com.intellij.ui.components.JBTabbedPane; import com.intellij.ui.components.JBTextField; import com.intellij.util.ui.JBUI; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.io.File; +import java.util.HashMap; +import java.util.Objects; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -64,13 +73,12 @@ public class GenerateSettingUI extends DialogWrapper { private JTextField tableNameField = new JBTextField(20); - private JButton columnSettingButton = new JButton("Column Setting"); private TextFieldWithBrowseButton moduleRootField = new TextFieldWithBrowseButton(); - private EditorTextFieldWithBrowseButton basePackageField; - private EditorTextFieldWithBrowseButton domainPackageField; - private EditorTextFieldWithBrowseButton mapperPackageField; - private EditorTextFieldWithBrowseButton examplePackageField; - private JTextField xmlPackageField = new JTextField(); + private TextFieldWithBrowseButton basePackageField = new TextFieldWithBrowseButton(); + private TextFieldWithBrowseButton domainPackageField = new TextFieldWithBrowseButton(); + private TextFieldWithBrowseButton mapperPackageField = new TextFieldWithBrowseButton(); + private TextFieldWithBrowseButton examplePackageField = new TextFieldWithBrowseButton(); + private TextFieldWithBrowseButton xmlPackageField = new TextFieldWithBrowseButton(); private JTextField mapperNameField = new JBTextField(20); private JTextField domainNameField = new JBTextField(20); private JTextField exampleNameField = new JBTextField(20); @@ -79,12 +87,13 @@ public class GenerateSettingUI extends DialogWrapper { private JPanel examplePackagePanel = new JPanel(); private JPanel exampleNamePanel = new JPanel(); - private JCheckBox offsetLimitBox = new JCheckBox("Pageable"); + private JComboBox mbgTargetRuntimeBox = new ComboBox<>(); + private JComboBox mbgJavaClientTypeBox = new ComboBox<>(); + private JCheckBox commentBox = new JCheckBox("Comment"); private JCheckBox overrideBox = new JCheckBox("Overwrite"); private JCheckBox needToStringHashcodeEqualsBox = new JCheckBox("toString/hashCode/equals"); private JCheckBox useSchemaPrefixBox = new JCheckBox("Use Schema Prefix"); - private JCheckBox needForUpdateBox = new JCheckBox("Add ForUpdate"); private JCheckBox annotationDAOBox = new JCheckBox("Repository Annotation"); private JCheckBox useDAOExtendStyleBox = new JCheckBox("Parent Interface"); private JCheckBox jsr310SupportBox = new JCheckBox("JSR310: Date and Time API"); @@ -92,18 +101,20 @@ public class GenerateSettingUI extends DialogWrapper { private JCheckBox useActualColumnNamesBox = new JCheckBox("Actual-Column"); private JCheckBox useTableNameAliasBox = new JCheckBox("Use-Alias"); private JCheckBox useExampleBox = new JCheckBox("Use Example"); - private JCheckBox mysql8Box = new JCheckBox("MySQL 8"); private JCheckBox lombokAnnotationBox = new JCheckBox("Lombok"); private JCheckBox lombokBuilderAnnotationBox = new JCheckBox("Lombok Builder"); - private JCheckBox swaggerAnnotationBox = new JCheckBox("Swagger Model"); private JBTabbedPane tabpanel = new JBTabbedPane(); - + private String basePackageInitialPath; + private String domainPackageInitialPath; + private String mapperPackageInitialPath; + private String examplePackageInitialPath; + private String xmlPackageInitialPath; public GenerateSettingUI(AnActionEvent anActionEvent) { super(anActionEvent.getData(PlatformDataKeys.PROJECT)); Project project = anActionEvent.getData(PlatformDataKeys.PROJECT); this.anActionEvent = anActionEvent; - this.project = anActionEvent.getData(PlatformDataKeys.PROJECT); + this.project = project; this.myBatisGeneratorConfiguration = MyBatisGeneratorConfiguration.getInstance(project); this.psiElements = anActionEvent.getData(LangDataKeys.PSI_ELEMENT_ARRAY); @@ -130,6 +141,30 @@ public GenerateSettingUI(AnActionEvent anActionEvent) { primaryKey = tableInfo.getPrimaryKeys().get(0); } + initTableConfig(globalConfig, historyConfigList, tableName, primaryKey); + VerticalFlowLayout layoutManager = new VerticalFlowLayout(VerticalFlowLayout.TOP); + layoutManager.setHgap(0); + layoutManager.setVgap(0); + contentPane.setLayout(layoutManager); + this.initHeader(tableName, primaryKey); + this.initGeneralPanel(entityName); + this.initOptionsPanel(); +// tabpanel.add(new ColumnTablePanel(tableConfig, tableInfo)); + contentPane.add(tabpanel); + tabpanel.setUI(new GenerateSettingTabUI()); + contentPane.setBorder(JBUI.Borders.empty()); + this.init(); + } + + /** + * 初始化 表相关配置 + * @param globalConfig + * @param historyConfigList + * @param tableName + * @param primaryKey + */ + private void initTableConfig(GlobalConfig globalConfig, Map historyConfigList, + String tableName, String primaryKey) { //单表时,优先使用已经存在的配置 if (historyConfigList != null) { tableConfig = historyConfigList.get(tableName); @@ -137,47 +172,29 @@ public GenerateSettingUI(AnActionEvent anActionEvent) { if (tableConfig == null) { //初始化配置 tableConfig = new TableConfig(); - tableConfig.setModuleRootPath(globalConfig.getModuleRootPath()); tableConfig.setSourcePath(globalConfig.getSourcePath()); tableConfig.setResourcePath(globalConfig.getResourcePath()); - tableConfig.setDomainPackage(globalConfig.getDomainPackage()); - tableConfig.setMapperPackage(globalConfig.getMapperPackage()); + tableConfig.setXmlPackage(globalConfig.getDefaultXmlPackage()); + tableConfig.setDomainPostfix(globalConfig.getDomainPostfix()); tableConfig.setMapperPostfix(globalConfig.getMapperPostfix()); tableConfig.setExamplePostfix(globalConfig.getExamplePostfix()); - tableConfig.setExamplePackage(globalConfig.getExamplePackage()); - tableConfig.setXmlPackage(globalConfig.getXmlPackage()); + //默认采用 MyBatis3DynamicSql 运行时 + tableConfig.setMgbTargetRuntime(MbgTargetRuntimeEnum.MY_BATIS3_DYNAMIC_SQL.name()); - tableConfig.setOffsetLimit(globalConfig.isOffsetLimit()); tableConfig.setComment(globalConfig.isComment()); tableConfig.setOverride(globalConfig.isOverride()); tableConfig.setNeedToStringHashcodeEquals(globalConfig.isNeedToStringHashcodeEquals()); tableConfig.setUseSchemaPrefix(globalConfig.isUseSchemaPrefix()); - tableConfig.setNeedForUpdate(globalConfig.isNeedForUpdate()); tableConfig.setAnnotationDAO(globalConfig.isAnnotationDAO()); tableConfig.setUseDAOExtendStyle(globalConfig.isUseDAOExtendStyle()); tableConfig.setJsr310Support(globalConfig.isJsr310Support()); tableConfig.setAnnotation(globalConfig.isAnnotation()); tableConfig.setUseActualColumnNames(globalConfig.isUseActualColumnNames()); - tableConfig.setUseTableNameAlias(globalConfig.isUseTableNameAlias()); tableConfig.setUseExample(globalConfig.isUseExample()); - tableConfig.setMysql8(globalConfig.isMysql8()); tableConfig.setLombokAnnotation(globalConfig.isLombokAnnotation()); tableConfig.setLombokBuilderAnnotation(globalConfig.isLombokBuilderAnnotation()); - tableConfig.setSwaggerAnnotation(globalConfig.isSwaggerAnnotation()); tableConfig.setPrimaryKey(primaryKey); } - VerticalFlowLayout layoutManager = new VerticalFlowLayout(VerticalFlowLayout.TOP); - layoutManager.setHgap(0); - layoutManager.setVgap(0); - contentPane.setLayout(layoutManager); - this.initHeader(tableName, primaryKey); - this.initGeneralPanel(entityName); - this.initOptionsPanel(); - tabpanel.add(new ColumnTablePanel(tableConfig, tableInfo)); - contentPane.add(tabpanel); - tabpanel.setUI(new GenerateSettingTabUI()); - contentPane.setBorder(JBUI.Borders.empty()); - this.init(); } @NotNull @@ -233,49 +250,34 @@ protected void doOKAction() { return; } - DbDataSource dbDataSource = null; - PsiElement current = psiElements[0]; - while (current != null) { - if (DbDataSource.class.isAssignableFrom(current.getClass())) { - dbDataSource = (DbDataSource) current; - break; - } - current = current.getParent(); - } - - if (dbDataSource == null) { - Messages.showMessageDialog(project, "Cannot get datasource", "Mybatis Generator Plus", Messages.getErrorIcon()); - return; - } - - RawConnectionConfig connectionConfig = dbDataSource.getConnectionConfig(); - + // todo get database username password from RawConnectionConfig + ConnectionConfig connectionConfig = getRawConnectionConfig(); if (connectionConfig == null) { - Messages.showMessageDialog(project, "Cannot get connection config", "Mybatis Generator Plus", Messages.getErrorIcon()); return; } - Map credentials = myBatisGeneratorConfiguration.getCredentials(); + if (MapUtils.isEmpty(credentials)) { + credentials = new HashMap<>(); + } Credential credential; - if (credentials == null || !credentials.containsKey(connectionConfig.getUrl())) { - boolean result = getDatabaseCredential(connectionConfig); - if (result) { - credentials = myBatisGeneratorConfiguration.getCredentials(); - credential = credentials.get(connectionConfig.getUrl()); - } else { - return; - } + if (!credentials.containsKey(connectionConfig.getUrl())) { + credential = new Credential(connectionConfig.getUrl()); + credentials.put(connectionConfig.getUrl(), credential); } else { credential = credentials.get(connectionConfig.getUrl()); } + if (org.apache.commons.lang3.StringUtils.isBlank(credential.getUsername()) + || org.apache.commons.lang3.StringUtils.isBlank(credential.getPwd())) { + getDatabaseCredential(credential); + myBatisGeneratorConfiguration.setCredentials(credentials); + } Callable callable = new Callable() { @Override public Exception call() { - String url = connectionConfig.getUrl(); - CredentialAttributes credentialAttributes = new CredentialAttributes(PluginContants.PLUGIN_NAME + "-" + url, credential.getUsername(), this.getClass(), false); - String password = PasswordSafe.getInstance().getPassword(credentialAttributes); try { - DatabaseUtils.testConnection(connectionConfig.getDriverClass(), connectionConfig.getUrl(), credential.getUsername(), password, mysql8Box.getSelectedObjects() != null); + DatabaseUtils.testConnection(connectionConfig.getDriverClass(), + connectionConfig.getUrl(), credential.getUsername(), + credential.getPwd(), connectionConfig.isMysql8()); } catch (ClassNotFoundException | SQLException e) { return e; } @@ -293,16 +295,6 @@ public Exception call() { } if (exception != null) { Messages.showMessageDialog(project, "Failed to connect to database \n " + exception.getMessage(), "Mybatis Generator Plus", Messages.getErrorIcon()); - if (exception.getClass().equals(SQLException.class)) { - SQLException sqlException = (SQLException) exception; - if (sqlException.getErrorCode() == 1045) { - boolean result = getDatabaseCredential(connectionConfig); - if (result) { - this.doOKAction(); - return; - } - } - } return; } @@ -324,46 +316,49 @@ public Exception call() { } - private boolean testConnection(RawConnectionConfig connectionConfig, Credential credential) { - String url = connectionConfig.getUrl(); - CredentialAttributes credentialAttributes = new CredentialAttributes(PluginContants.PLUGIN_NAME + "-" + url, credential.getUsername(), this.getClass(), false); - String password = PasswordSafe.getInstance().getPassword(credentialAttributes); - try { - DatabaseUtils.testConnection(connectionConfig.getDriverClass(), connectionConfig.getUrl(), credential.getUsername(), password, mysql8Box.getSelectedObjects() != null); - return true; - } catch (ClassNotFoundException e) { - Messages.showMessageDialog(project, "Failed to connect to database \n " + e.getMessage(), "Mybatis Generator Plus", Messages.getErrorIcon()); - e.printStackTrace(); - return false; - } catch (SQLException e) { - Messages.showMessageDialog(project, "Failed to connect to database \n " + e.getMessage(), "Mybatis Generator Plus", Messages.getErrorIcon()); - if (e.getErrorCode() == 1045) { - boolean result = getDatabaseCredential(connectionConfig); - if (result) { - Map credentials = myBatisGeneratorConfiguration.getCredentials(); - return testConnection(connectionConfig, credentials.get(connectionConfig.getUrl())); - } else { - return false; - } - } else { - return false; - } + /** + * 获取选中的表的数据库连接 + * @return + */ + private ConnectionConfig getRawConnectionConfig() { + PsiElement psiElement = psiElements[0]; + DbDataSource dbDataSource = (DbDataSource) psiElement.getParent().getParent(); + DbNamespace dbNamespace = (DbNamespace) psiElement.getParent(); + + + if (dbDataSource == null) { + Messages.showMessageDialog(project, "Cannot get datasource", "Mybatis Generator Plus", Messages.getErrorIcon()); + return null; } + + String schema = dbNamespace.getName(); + RawConnectionConfig connectionConfig = dbDataSource.getConnectionConfig(); + + if (connectionConfig == null) { + Messages.showMessageDialog(project, "Cannot get connection config", "Mybatis Generator Plus", Messages.getErrorIcon()); + return null; + } + ConnectionConfig config = new ConnectionConfig(connectionConfig.getName(), + connectionConfig.getDriverClass(), connectionConfig.getUrl()); + NameVersion databaseVersion = dbDataSource.getDatabaseVersion(); + config.setDataBaseName(databaseVersion.name); + config.setDataBaseVersion(databaseVersion.version); + config.setSchema(schema); + return config; } - private boolean getDatabaseCredential(RawConnectionConfig connectionConfig) { - DatabaseCredentialUI databaseCredentialUI = new DatabaseCredentialUI(anActionEvent.getProject(), connectionConfig.getUrl()); + + private boolean getDatabaseCredential(Credential credential) { + DatabaseCredentialUI databaseCredentialUI = new DatabaseCredentialUI(anActionEvent.getProject(), credential); return databaseCredentialUI.showAndGet(); } private void initOptionsPanel() { JBPanel optionsPanel = new JBPanel(new GridLayout(8, 4, 10, 10)); - optionsPanel.add(offsetLimitBox); optionsPanel.add(commentBox); optionsPanel.add(overrideBox); optionsPanel.add(needToStringHashcodeEqualsBox); optionsPanel.add(useSchemaPrefixBox); - optionsPanel.add(needForUpdateBox); optionsPanel.add(annotationDAOBox); optionsPanel.add(useDAOExtendStyleBox); optionsPanel.add(jsr310SupportBox); @@ -371,22 +366,22 @@ private void initOptionsPanel() { optionsPanel.add(useActualColumnNamesBox); optionsPanel.add(useTableNameAliasBox); optionsPanel.add(useExampleBox); - optionsPanel.add(mysql8Box); optionsPanel.add(lombokAnnotationBox); optionsPanel.add(lombokBuilderAnnotationBox); - optionsPanel.add(swaggerAnnotationBox); + + useExampleBox.setVisible(mbgJavaClientTypeBox.isVisible()); useExampleBox.addChangeListener(e -> { - exampleNamePanel.setVisible(useExampleBox.getSelectedObjects() != null); - examplePackagePanel.setVisible(useExampleBox.getSelectedObjects() != null); + exampleNamePanel.setVisible( + mbgJavaClientTypeBox.isVisible() && useExampleBox.getSelectedObjects() != null); + examplePackagePanel.setVisible( + mbgJavaClientTypeBox.isVisible() && useExampleBox.getSelectedObjects() != null); }); - offsetLimitBox.setSelected(tableConfig.isOffsetLimit()); commentBox.setSelected(tableConfig.isComment()); overrideBox.setSelected(tableConfig.isOverride()); needToStringHashcodeEqualsBox.setSelected(tableConfig.isNeedToStringHashcodeEquals()); useSchemaPrefixBox.setSelected(tableConfig.isUseSchemaPrefix()); - needForUpdateBox.setSelected(tableConfig.isNeedForUpdate()); annotationDAOBox.setSelected(tableConfig.isAnnotationDAO()); useDAOExtendStyleBox.setSelected(tableConfig.isUseDAOExtendStyle()); jsr310SupportBox.setSelected(tableConfig.isJsr310Support()); @@ -394,10 +389,8 @@ private void initOptionsPanel() { useActualColumnNamesBox.setSelected(tableConfig.isUseActualColumnNames()); useTableNameAliasBox.setSelected(tableConfig.isUseTableNameAlias()); useExampleBox.setSelected(tableConfig.isUseExample()); - mysql8Box.setSelected(tableConfig.isMysql8()); lombokAnnotationBox.setSelected(tableConfig.isLombokAnnotation()); lombokBuilderAnnotationBox.setSelected(tableConfig.isLombokBuilderAnnotation()); - swaggerAnnotationBox.setSelected(tableConfig.isSwaggerAnnotation()); optionsPanel.setName("Options"); tabpanel.add(optionsPanel); } @@ -414,15 +407,18 @@ private void initHeader(String tableName, String primaryKey) { JPanel moduleRootPanel = new JPanel(); moduleRootPanel.setLayout(new BoxLayout(moduleRootPanel, BoxLayout.X_AXIS)); JBLabel projectRootLabel = new JBLabel("Module Root:"); - projectRootLabel.setPreferredSize(new Dimension(150, 10)); - moduleRootField.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFolderDescriptor()) { +// projectRootLabel.setPreferredSize(new Dimension(150, 10)); + moduleRootField.addBrowseFolderListener(new TextBrowseFolderListener( + FileChooserDescriptorFactory.createSingleFolderDescriptor()) { @Override public void actionPerformed(ActionEvent e) { super.actionPerformed(e); - moduleRootField.setText(moduleRootField.getText().replaceAll("\\\\", "/")); + //修改package选择器初始路径 + initPackageInitialPath(moduleRootField.getText()); } }); if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getModuleRootPath())) { + //历史值 moduleRootField.setText(tableConfig.getModuleRootPath()); } else { moduleRootField.setText(project.getBasePath()); @@ -435,7 +431,7 @@ public void actionPerformed(ActionEvent e) { tableNamePanel.setLayout(new BoxLayout(tableNamePanel, BoxLayout.X_AXIS)); JLabel tableLabel = new JLabel("Table Name:"); tableLabel.setLabelFor(tableNameField); - tableLabel.setPreferredSize(new Dimension(150, 10)); +// tableLabel.setPreferredSize(new Dimension(150, 10)); tableNamePanel.add(tableLabel); tableNamePanel.add(tableNameField); @@ -448,10 +444,10 @@ public void actionPerformed(ActionEvent e) { tableNameField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { - String entityName = StringUtils.dbStringToCamelStyle(tableNameField.getText()); - domainNameField.setText(entityName); - mapperNameField.setText(getMapperName(entityName)); - exampleNameField.setText(getExampleName(entityName)); + String domainName = StringUtils.dbStringToCamelStyle(tableNameField.getText()); + domainNameField.setText(domainName); + mapperNameField.setText(getMapperName(domainName)); + exampleNameField.setText(getExampleName(domainName)); } }); @@ -459,7 +455,7 @@ public void keyReleased(KeyEvent e) { primaryPanel.setLayout(new BoxLayout(primaryPanel, BoxLayout.X_AXIS)); JLabel primaryKeyLabel = new JLabel(" Primary Key:"); primaryKeyLabel.setLabelFor(primaryKeyField); - primaryKeyLabel.setPreferredSize(new Dimension(150, 10)); +// primaryKeyLabel.setPreferredSize(new Dimension(150, 10)); tableNamePanel.add(primaryKeyLabel); tableNamePanel.add(primaryKeyField); @@ -471,31 +467,197 @@ public void keyReleased(KeyEvent e) { contentPane.add(headerPanel); } - private void initGeneralPanel(String modelName) { - JPanel domainNamePanel = new JPanel(); - domainNamePanel.setLayout(new BoxLayout(domainNamePanel, BoxLayout.X_AXIS)); - JLabel entityNameLabel = new JLabel("Domain Name:"); - entityNameLabel.setPreferredSize(new Dimension(150, 10)); - domainNamePanel.add(entityNameLabel); - domainNamePanel.add(domainNameField); - if (psiElements.length > 1) { - domainNameField.addFocusListener(new JTextFieldHintListener(domainNameField, "eg:DbTable")); - } else { - domainNameField.setText(modelName); - } - domainNameField.addKeyListener(new KeyAdapter() { + private void initPackageInitialPath(String moduleRootPath) { + basePackageInitialPath = moduleRootPath + File.separator + tableConfig.getSourcePath(); + domainPackageInitialPath = moduleRootPath + File.separator + tableConfig.getSourcePath(); + mapperPackageInitialPath = moduleRootPath + File.separator + tableConfig.getSourcePath(); + examplePackageInitialPath = moduleRootPath + File.separator + tableConfig.getSourcePath(); + xmlPackageInitialPath = moduleRootPath + File.separator + tableConfig.getResourcePath(); + } + + private void initGeneralPanel(String domainName) { + JPanel mgbTargetRuntimePanel = initMbgTargbgetRuntimePanel(); + JPanel domainNamePanel = initDomainNamePanel(domainName); + JPanel mapperNamePanel = initMapperNamePanel(domainName); + initExampleNamePanel(domainName); + initPackageInitialPath(moduleRootField.getText()); + JPanel basePackagePanel = initPackagePanel("Base Package:", + Objects.nonNull(tableConfig) ? tableConfig.getBasePackage() : "", basePackageField, + PackageTypeEnum.BASE); + JPanel domainPackagePanel = initPackagePanel("Domain Package:", + Objects.nonNull(tableConfig) ? tableConfig.getDomainPackage() : "", domainPackageField, + PackageTypeEnum.DOMAIN); + JPanel mapperPackagePanel = initPackagePanel("Mapper Package:", + Objects.nonNull(tableConfig) ? tableConfig.getMapperPackage() : "", mapperPackageField, + PackageTypeEnum.MAPPER); + examplePackagePanel = initPackagePanel("Example Package:", + Objects.nonNull(tableConfig) ? tableConfig.getExamplePackage() : "", + examplePackageField, PackageTypeEnum.EXAMPLE); + examplePackagePanel.setVisible( + mbgJavaClientTypeBox.isVisible() && useExampleBox.getSelectedObjects() != null); + JPanel xmlPackagePanel = initPackagePanel("Xml Package:", + Objects.nonNull(tableConfig) ? tableConfig.getXmlPackage() : "", xmlPackageField, + PackageTypeEnum.XML); + xmlPackageField.setVisible(mbgJavaClientTypeBox.isVisible()); + xmlPackagePanel.setVisible(mbgJavaClientTypeBox.isVisible()); + + JPanel generalPanel = new JPanel(); + generalPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); + + // ******** Runtime & Type ui ********* + generalPanel.add(new TitledSeparator("Runtime And Type")); + JPanel runtimePanel = new JPanel(); + runtimePanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); + runtimePanel.add(mgbTargetRuntimePanel); + generalPanel.add(runtimePanel); + + // ******** Domain ui ********* + generalPanel.add(new TitledSeparator("Domain")); + JPanel domainPanel = new JPanel(); + domainPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); + domainPanel.add(domainNamePanel); + domainPanel.add(mapperNamePanel); + domainPanel.add(exampleNamePanel); + generalPanel.add(domainPanel); + + // ******** Package ui ********* + generalPanel.add(new TitledSeparator("Package")); + JPanel packagePanel = new JPanel(); + packagePanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); + packagePanel.add(basePackagePanel); + packagePanel.add(domainPackagePanel); + packagePanel.add(mapperPackagePanel); + packagePanel.add(examplePackagePanel); + packagePanel.add(xmlPackagePanel); + generalPanel.add(packagePanel); + + generalPanel.setName("General"); + tabpanel.add(generalPanel); + } + + + @NotNull + private JPanel initPackagePanel(String labelText, String historyFieldText, + TextFieldWithBrowseButton textFieldWithBrowseButton, PackageTypeEnum packageType) { + + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); + JBLabel label = new JBLabel(labelText); +// label.setPreferredSize(new Dimension(150, 10)); + textFieldWithBrowseButton.setText(historyFieldText); + textFieldWithBrowseButton.setEditable(true); + textFieldWithBrowseButton.addBrowseFolderListener(new TextBrowseFolderListener( + FileChooserDescriptorFactory.createSingleFolderDescriptor()) { @Override - public void keyReleased(KeyEvent e) { - mapperNameField.setText(getMapperName(domainNameField.getText())); - exampleNameField.setText(getExampleName(domainNameField.getText())); + protected VirtualFile getInitialFile() { + String initialPath = ""; + switch (packageType) { + case BASE: + initialPath = basePackageInitialPath; + break; + case DOMAIN: + initialPath = domainPackageInitialPath; + break; + case MAPPER: + initialPath = mapperPackageInitialPath; + break; + case EXAMPLE: + initialPath = examplePackageInitialPath; + break; + case XML: + initialPath = xmlPackageInitialPath; + break; + } + VirtualFile virtualFile = LocalFileSystem.getInstance() + .findFileByPath(initialPath); + return virtualFile; + } + + @Override + protected String chosenFileToResultingText(@NotNull VirtualFile chosenFile) { + //选择的绝对路径 + String choosedAbsolutePath = chosenFile.getPresentableUrl(); + //将项目根路径去掉,得到相对路径 + String relativePath = choosedAbsolutePath.replace(moduleRootField.getText(), ""); + //将源码文件路径(source path)和配置文件(resource path)路径去掉 + String packagePath = relativePath.replace(tableConfig.getSourcePath(), "") + .replace(tableConfig.getResourcePath(), "").replaceAll(File.separator, "."); + if (packagePath.startsWith("..")) { + packagePath = packagePath.substring(2, packagePath.length()); + } else { + packagePath = ""; + } + switch (packageType) { + case BASE: + if (org.apache.commons.lang3.StringUtils.isBlank(packagePath)) { + domainPackageField.setText("entity"); + mapperPackageField.setText("mapper"); + if (examplePackageField.isVisible()) { + examplePackageField.setText("example"); + } + }else { + domainPackageField.setText(packagePath + ".entity"); + mapperPackageField.setText(packagePath + ".mapper"); + if (examplePackageField.isVisible()) { + examplePackageField.setText(packagePath + ".example"); + } + } + xmlPackageField.setText(tableConfig.getXmlPackage()); + basePackageInitialPath = choosedAbsolutePath; + domainPackageInitialPath = choosedAbsolutePath; + mapperPackageInitialPath = choosedAbsolutePath; + examplePackageInitialPath = choosedAbsolutePath; + break; + case DOMAIN: + domainPackageInitialPath = choosedAbsolutePath; + break; + case MAPPER: + mapperPackageInitialPath = choosedAbsolutePath; + break; + case EXAMPLE: + examplePackageInitialPath = choosedAbsolutePath; + break; + case XML: + xmlPackageInitialPath = choosedAbsolutePath; + if (org.apache.commons.lang3.StringUtils.isBlank(packagePath)) { + packagePath = tableConfig.getXmlPackage(); + } + break; + } + return packagePath; } }); + panel.add(label); + panel.add(textFieldWithBrowseButton); + return panel; + } + private void initExampleNamePanel(String domainName) { + exampleNamePanel.setLayout(new BoxLayout(exampleNamePanel, BoxLayout.X_AXIS)); + JLabel exampleNameLabel = new JLabel("Example Name:"); +// exampleNameLabel.setPreferredSize(new Dimension(150, 10)); + exampleNameLabel.setLabelFor(domainNameField); + exampleNamePanel.add(exampleNameLabel); + exampleNamePanel.add(exampleNameField); + if (psiElements.length > 1) { + if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getExamplePostfix())) { + exampleNameField.addFocusListener(new JTextFieldHintListener(exampleNameField, "eg:DbTable" + tableConfig.getExamplePostfix())); + } else { + exampleNameField.addFocusListener(new JTextFieldHintListener(exampleNameField, "eg:DbTable" + "Example")); + } + } else { + exampleNameField.setText(getExampleName(domainName)); + } + exampleNamePanel.setVisible(mbgJavaClientTypeBox.isVisible() && tableConfig.isUseExample()); + } + + @NotNull + private JPanel initMapperNamePanel(String domainName) { //MapperName JPanel mapperNamePanel = new JPanel(); mapperNamePanel.setLayout(new BoxLayout(mapperNamePanel, BoxLayout.X_AXIS)); JLabel mapperNameLabel = new JLabel("Mapper Name:"); - mapperNameLabel.setPreferredSize(new Dimension(150, 10)); +// mapperNameLabel.setPreferredSize(new Dimension(150, 10)); mapperNameLabel.setLabelFor(domainNameField); mapperNamePanel.add(mapperNameLabel); mapperNamePanel.add(mapperNameField); @@ -506,169 +668,118 @@ public void keyReleased(KeyEvent e) { mapperNameField.addFocusListener(new JTextFieldHintListener(mapperNameField, "eg:DbTable" + "Mapper")); } } else { - mapperNameField.setText(getMapperName(modelName)); + mapperNameField.setText(getMapperName(domainName)); } + return mapperNamePanel; + } - exampleNamePanel.setLayout(new BoxLayout(exampleNamePanel, BoxLayout.X_AXIS)); - JLabel exampleNameLabel = new JLabel("Example Name:"); - exampleNameLabel.setPreferredSize(new Dimension(150, 10)); - exampleNameLabel.setLabelFor(domainNameField); - exampleNamePanel.add(exampleNameLabel); - exampleNamePanel.add(exampleNameField); + @NotNull + private JPanel initDomainNamePanel(String domainName) { + //domainName + JPanel domainNamePanel = new JPanel(); + domainNamePanel.setLayout(new BoxLayout(domainNamePanel, BoxLayout.X_AXIS)); + JLabel entityNameLabel = new JLabel("Domain Name:"); +// entityNameLabel.setPreferredSize(new Dimension(150, 10)); + domainNamePanel.add(entityNameLabel); + domainNamePanel.add(domainNameField); if (psiElements.length > 1) { - if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getExamplePostfix())) { - exampleNameField.addFocusListener(new JTextFieldHintListener(exampleNameField, "eg:DbTable" + tableConfig.getExamplePostfix())); - } else { - exampleNameField.addFocusListener(new JTextFieldHintListener(exampleNameField, "eg:DbTable" + "Example")); + if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getDomainPostfix())){ + domainNameField.addFocusListener(new JTextFieldHintListener(domainNameField, + "eg:DbTable" + tableConfig.getDomainPostfix())); + }else { + domainNameField.addFocusListener( + new JTextFieldHintListener(domainNameField, "eg:DbTable" + "Entity")); } } else { - exampleNameField.setText(getExampleName(modelName)); + domainNameField.setText(domainName + "Entity"); } - - exampleNamePanel.setVisible(tableConfig.isUseExample()); - - - JPanel basePackagePanel = new JPanel(); - basePackagePanel.setLayout(new BoxLayout(basePackagePanel, BoxLayout.X_AXIS)); - JBLabel basePackageLabel = new JBLabel("Base Package:"); - basePackageLabel.setPreferredSize(new Dimension(150, 10)); - basePackageField = new EditorTextFieldWithBrowseButton(project, false); - basePackageField.addActionListener(e -> { - final PackageChooserDialog chooser = new PackageChooserDialog("Select Base Package", project); - chooser.selectPackage(basePackageField.getText()); - chooser.show(); - final PsiPackage psiPackage = chooser.getSelectedPackage(); - String packageName = psiPackage == null ? null : psiPackage.getQualifiedName(); - if (!StringUtils.isEmpty(packageName)) { - basePackageField.setText(packageName); - domainPackageField.setText(packageName + ".domain"); - mapperPackageField.setText(packageName + "." + getMapperPostfix().toLowerCase()); - examplePackageField.setText(packageName + "." + getExamplePostfix().toLowerCase()); - } - }); - basePackageField.addKeyListener(new KeyAdapter() { + domainNameField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { - domainPackageField.setText(basePackageField.getText() + ".domain"); - mapperPackageField.setText(basePackageField.getText() + "." + getMapperPostfix().toLowerCase()); - examplePackageField.setText(basePackageField.getText() + "." + getExamplePostfix().toLowerCase()); + mapperNameField.setText(getMapperName(domainNameField.getText())); + exampleNameField.setText(getExampleName(domainNameField.getText())); } }); - if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getBasePackage())) { - basePackageField.setText(tableConfig.getBasePackage()); - } else { - basePackageField.setText(""); - } - basePackagePanel.add(basePackageLabel); - basePackagePanel.add(basePackageField); - - this.domainPackageField = new EditorTextFieldWithBrowseButton(project, false); - - - JPanel entityPackagePanel = new JPanel(); - entityPackagePanel.setLayout(new BoxLayout(entityPackagePanel, BoxLayout.X_AXIS)); - JBLabel entityPackageLabel = new JBLabel("Domain Package:"); - entityPackageLabel.setPreferredSize(new Dimension(150, 10)); - domainPackageField.addActionListener(e -> { - final PackageChooserDialog chooser = new PackageChooserDialog("Select Entity Package", project); - chooser.selectPackage(domainPackageField.getText()); - chooser.show(); - final PsiPackage psiPackage = chooser.getSelectedPackage(); - String packageName = psiPackage == null ? null : psiPackage.getQualifiedName(); - if (!StringUtils.isEmpty(packageName)) { - domainPackageField.setText(packageName); + return domainNamePanel; + } + + @NotNull + private JPanel initMbgTargbgetRuntimePanel() { + JPanel jPanel = new JPanel(); + jPanel.setLayout(new GridLayout(1, 2, 160, 0)); + + // mbgTargetRuntime + JPanel runtimePanel = new JPanel(); + runtimePanel.setLayout(new BoxLayout(runtimePanel, BoxLayout.X_AXIS)); + JLabel runtimeLabel = new JLabel("Target Runtime:"); + runtimePanel.add(runtimeLabel); + for (MbgTargetRuntimeEnum value : MbgTargetRuntimeEnum.values()) { + mbgTargetRuntimeBox.addItem(value.getName()); + } + if (org.apache.commons.lang3.StringUtils.isNotBlank(tableConfig.getMgbTargetRuntime())) { + mbgTargetRuntimeBox.setSelectedItem(tableConfig.getMgbTargetRuntime()); + }else { + mbgTargetRuntimeBox.setSelectedIndex(0); + } + mbgTargetRuntimeBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent event) { + if (Objects.equals(event.getStateChange(), ItemEvent.SELECTED)) { + // 根据当前选中的runtime 修改可供选择的client type + MbgTargetRuntimeEnum runtimeEnum = MbgTargetRuntimeEnum.getByName( + event.getItem().toString()); + List clientTypeList = MbgJavaClientConfigTypeEnum.getValuesByTargetRuntime( + runtimeEnum); + if (CollectionUtils.isNotEmpty(clientTypeList)) { + mbgJavaClientTypeBox.removeAllItems(); + for (String type : clientTypeList) { + mbgJavaClientTypeBox.addItem(type); + } + mbgJavaClientTypeBox.getParent().setVisible(true); + mbgJavaClientTypeBox.setVisible(true); + }else { + mbgJavaClientTypeBox.getParent().setVisible(false); + mbgJavaClientTypeBox.setVisible(false); + } + // MyBatis3DynamicSql & MyBatis3Kotlin 模式下没有 example 和 xml + exampleNamePanel.setVisible(mbgJavaClientTypeBox.isVisible()); + examplePackagePanel.setVisible(mbgJavaClientTypeBox.isVisible()); + xmlPackageField.getParent().setVisible(mbgJavaClientTypeBox.isVisible()); + xmlPackageField.setVisible(mbgJavaClientTypeBox.isVisible()); + useExampleBox.setVisible(mbgJavaClientTypeBox.isVisible()); + } } }); - if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getDomainPackage())) { - domainPackageField.setText(tableConfig.getDomainPackage()); - } else { - domainPackageField.setText(""); - } - entityPackagePanel.add(entityPackageLabel); - entityPackagePanel.add(domainPackageField); - - JPanel mapperPackagePanel = new JPanel(); - mapperPackagePanel.setLayout(new BoxLayout(mapperPackagePanel, BoxLayout.X_AXIS)); - JLabel mapperPackageLabel = new JLabel("Mapper Package:"); - mapperPackageLabel.setPreferredSize(new Dimension(150, 10)); - mapperPackageField = new EditorTextFieldWithBrowseButton(project, false); - mapperPackageField.addActionListener(event -> { - final PackageChooserDialog packageChooserDialog = new PackageChooserDialog("Select Mapper Package", project); - packageChooserDialog.selectPackage(mapperPackageField.getText()); - packageChooserDialog.show(); - - final PsiPackage psiPackage = packageChooserDialog.getSelectedPackage(); - String packageName = psiPackage == null ? null : psiPackage.getQualifiedName(); - if (!StringUtils.isEmpty(packageName)) { - mapperPackageField.setText(packageName); + runtimePanel.add(mbgTargetRuntimeBox); + jPanel.add(runtimePanel); + + // java client type + JPanel typePanel = new JPanel(); + typePanel.setLayout(new BoxLayout(typePanel, BoxLayout.X_AXIS)); + JLabel clientTypeLabel = new JLabel("Client Type:"); + typePanel.add(clientTypeLabel); + List typeList = MbgJavaClientConfigTypeEnum.getValuesByTargetRuntime( + MbgTargetRuntimeEnum.getByName(mbgTargetRuntimeBox.getSelectedItem().toString())); + if (CollectionUtils.isNotEmpty(typeList)) { + for (String type : typeList) { + mbgJavaClientTypeBox.addItem(type); } - }); - if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getMapperPackage())) { - mapperPackageField.setText(tableConfig.getMapperPackage()); - } else { - mapperPackageField.setText(""); - } - mapperPackagePanel.add(mapperPackageLabel); - mapperPackagePanel.add(mapperPackageField); - - examplePackagePanel.setLayout(new BoxLayout(examplePackagePanel, BoxLayout.X_AXIS)); - - examplePackageField = new EditorTextFieldWithBrowseButton(project, false); - examplePackageField.addActionListener(e -> { - final PackageChooserDialog packageChooserDialog = new PackageChooserDialog("Select Example Package", project); - packageChooserDialog.selectPackage(examplePackageField.getText()); - packageChooserDialog.show(); - - final PsiPackage psiPackage = packageChooserDialog.getSelectedPackage(); - String packageName = psiPackage == null ? null : psiPackage.getQualifiedName(); - if (!StringUtils.isEmpty(packageName)) { - examplePackageField.setText(packageName); + if (org.apache.commons.lang3.StringUtils.isNotBlank(tableConfig.getMgbJavaClientConfigType())) { + mbgJavaClientTypeBox.setSelectedItem(tableConfig.getMgbJavaClientConfigType()); + }else { + mbgJavaClientTypeBox.setSelectedIndex(0); } - }); - - JLabel examplePackageLabel = new JLabel("Example Package:"); - examplePackageLabel.setPreferredSize(new Dimension(150, 10)); - examplePackageField.setText(tableConfig.getExamplePackage()); - examplePackagePanel.add(examplePackageLabel); - examplePackagePanel.add(examplePackageField); - examplePackagePanel.setVisible(tableConfig.isUseExample()); - - JPanel xmlPackagePanel = new JPanel(); - xmlPackagePanel.setLayout(new BoxLayout(xmlPackagePanel, BoxLayout.X_AXIS)); - JLabel xmlPackageLabel = new JLabel("Xml Package:"); - xmlPackageLabel.setPreferredSize(new Dimension(150, 10)); - xmlPackageField.setText(tableConfig.getXmlPackage()); - xmlPackagePanel.add(xmlPackageLabel); - xmlPackagePanel.add(xmlPackageField); - - JPanel generalPanel = new JPanel(); - generalPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); - generalPanel.add(new TitledSeparator("Domain")); - - JPanel domainPanel = new JPanel(); - domainPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); - - domainPanel.add(domainNamePanel); - domainPanel.add(mapperNamePanel); - domainPanel.add(exampleNamePanel); - generalPanel.add(domainPanel); - - generalPanel.add(new TitledSeparator("Package")); - - JPanel packagePanel = new JPanel(); - packagePanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); + }else { + typePanel.setVisible(false); + mbgJavaClientTypeBox.setVisible(false); + } + typePanel.add(mbgJavaClientTypeBox); + jPanel.add(typePanel); - packagePanel.add(basePackagePanel); - packagePanel.add(entityPackagePanel); - packagePanel.add(mapperPackagePanel); - packagePanel.add(examplePackagePanel); - packagePanel.add(xmlPackagePanel); - generalPanel.add(packagePanel); - generalPanel.setName("General"); - tabpanel.add(generalPanel); + return jPanel; } - public void generate(RawConnectionConfig connectionConfig) { + public void generate(ConnectionConfig connectionConfig) { tableConfig.setName(tableNameField.getText()); tableConfig.setTableName(tableNameField.getText()); tableConfig.setModuleRootPath(moduleRootField.getText()); @@ -684,12 +795,13 @@ public void generate(RawConnectionConfig connectionConfig) { tableConfig.setPrimaryKey(primaryKeyField.getText()); tableConfig.setExampleName(exampleNameField.getText()); - tableConfig.setOffsetLimit(offsetLimitBox.getSelectedObjects() != null); + tableConfig.setMgbTargetRuntime((String) mbgTargetRuntimeBox.getSelectedItem()); + tableConfig.setMgbJavaClientConfigType((String) mbgJavaClientTypeBox.getSelectedItem()); + tableConfig.setComment(commentBox.getSelectedObjects() != null); tableConfig.setOverride(overrideBox.getSelectedObjects() != null); tableConfig.setNeedToStringHashcodeEquals(needToStringHashcodeEqualsBox.getSelectedObjects() != null); tableConfig.setUseSchemaPrefix(useSchemaPrefixBox.getSelectedObjects() != null); - tableConfig.setNeedForUpdate(needForUpdateBox.getSelectedObjects() != null); tableConfig.setAnnotationDAO(annotationDAOBox.getSelectedObjects() != null); tableConfig.setUseDAOExtendStyle(useDAOExtendStyleBox.getSelectedObjects() != null); tableConfig.setJsr310Support(jsr310SupportBox.getSelectedObjects() != null); @@ -697,10 +809,9 @@ public void generate(RawConnectionConfig connectionConfig) { tableConfig.setUseActualColumnNames(useActualColumnNamesBox.getSelectedObjects() != null); tableConfig.setUseTableNameAlias(useTableNameAliasBox.getSelectedObjects() != null); tableConfig.setUseExample(useExampleBox.getSelectedObjects() != null); - tableConfig.setMysql8(mysql8Box.getSelectedObjects() != null); + tableConfig.setMysql8(connectionConfig.isMysql8()); tableConfig.setLombokAnnotation(lombokAnnotationBox.getSelectedObjects() != null); tableConfig.setLombokBuilderAnnotation(lombokBuilderAnnotationBox.getSelectedObjects() != null); - tableConfig.setSwaggerAnnotation(swaggerAnnotationBox.getSelectedObjects() != null); tableConfig.setSourcePath(this.tableConfig.getSourcePath()); tableConfig.setResourcePath(this.tableConfig.getResourcePath()); @@ -708,27 +819,11 @@ public void generate(RawConnectionConfig connectionConfig) { } - private String getMapperName(String entityName) { + private String getMapperName(String domainName) { if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getMapperPostfix())) { - return entityName + tableConfig.getMapperPostfix(); - } else { - return (entityName + "Mapper"); - } - } - - private String getMapperPostfix() { - if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getMapperPostfix())) { - return tableConfig.getMapperPostfix(); - } else { - return "Mapper"; - } - } - - private String getExamplePostfix() { - if (tableConfig != null && !StringUtils.isEmpty(tableConfig.getExamplePostfix())) { - return tableConfig.getExamplePostfix(); + return domainName + tableConfig.getMapperPostfix(); } else { - return "Example"; + return (domainName + "Mapper"); } } diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/ui/GeneratorSettingUI.java b/src/com/github/leecho/idea/plugin/mybatis/generator/ui/GeneratorSettingUI.java index 081ed97..00f014f 100644 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/ui/GeneratorSettingUI.java +++ b/src/com/github/leecho/idea/plugin/mybatis/generator/ui/GeneratorSettingUI.java @@ -1,24 +1,31 @@ package com.github.leecho.idea.plugin.mybatis.generator.ui; +import com.github.leecho.idea.plugin.mybatis.generator.enums.MbgJavaClientConfigTypeEnum; +import com.github.leecho.idea.plugin.mybatis.generator.enums.MbgTargetRuntimeEnum; import com.github.leecho.idea.plugin.mybatis.generator.model.GlobalConfig; import com.github.leecho.idea.plugin.mybatis.generator.setting.MyBatisGeneratorConfiguration; -import com.github.leecho.idea.plugin.mybatis.generator.util.StringUtils; -import com.intellij.ide.util.PackageChooserDialog; -import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; import com.intellij.openapi.project.Project; +import com.intellij.openapi.ui.ComboBox; import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.ui.TextBrowseFolderListener; -import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.ui.VerticalFlowLayout; -import com.intellij.psi.PsiPackage; -import com.intellij.ui.EditorTextFieldWithBrowseButton; import com.intellij.ui.TitledSeparator; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBPanel; - -import javax.swing.*; -import java.awt.*; -import java.awt.event.ActionEvent; +import java.awt.GridLayout; +import java.awt.event.ItemEvent; +import java.awt.event.ItemListener; +import java.util.List; +import java.util.Objects; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; /** * 设置界面 @@ -29,26 +36,24 @@ public class GeneratorSettingUI extends JDialog { private Project project; - private EditorTextFieldWithBrowseButton domainPackageField; - private EditorTextFieldWithBrowseButton mapperPackageField; - private JTextField xmlPackageField = new JTextField(); - private EditorTextFieldWithBrowseButton examplePackageField; - private TextFieldWithBrowseButton moduleRootField = new TextFieldWithBrowseButton(); - private JTextField sourcePathField = new JTextField(); private JTextField resourcePathField = new JTextField(); private JTextField tablePrefixField = new JTextField(10); + private JTextField domainPostfixField = new JTextField(10); private JTextField mapperPostfixField = new JTextField(10); + private JPanel examplePostfixPanel = new JPanel(); private JTextField examplePostfixField = new JTextField(10); + private JTextField xmlPackageField = new JTextField(10); + + private JComboBox mbgTargetRuntimeBox = new ComboBox<>(); + private JComboBox mbgJavaClientTypeBox = new ComboBox<>(); - private JCheckBox offsetLimitBox = new JCheckBox("Pageable"); private JCheckBox commentBox = new JCheckBox("Comment"); private JCheckBox overrideBox = new JCheckBox("Overwrite"); private JCheckBox needToStringHashcodeEqualsBox = new JCheckBox("toString/hashCode/equals"); - private JCheckBox useSchemaPrefixBox = new JCheckBox("Use Schema Prefix"); - private JCheckBox needForUpdateBox = new JCheckBox("Add ForUpdate"); + private final JCheckBox useSchemaPrefixBox = new JCheckBox("Use Schema Prefix"); private JCheckBox annotationDAOBox = new JCheckBox("Repository Annotation"); private JCheckBox useDAOExtendStyleBox = new JCheckBox("Parent Interface"); private JCheckBox jsr310SupportBox = new JCheckBox("JSR310: Date and Time API"); @@ -56,10 +61,8 @@ public class GeneratorSettingUI extends JDialog { private JCheckBox useActualColumnNamesBox = new JCheckBox("Actual-Column"); private JCheckBox useTableNameAliasBox = new JCheckBox("Use-Alias"); private JCheckBox useExampleBox = new JCheckBox("Use Example"); - private JCheckBox mysql8Box = new JCheckBox("MySQL 8"); private JCheckBox lombokAnnotationBox = new JCheckBox("Lombok"); private JCheckBox lombokBuilderAnnotationBox = new JCheckBox("Lombok Builder"); - private JCheckBox swaggerAnnotationBox = new JCheckBox("Swagger Model"); private MyBatisGeneratorConfiguration config; @@ -75,23 +78,98 @@ public void createUI(Project project) { config = MyBatisGeneratorConfiguration.getInstance(project); + this.initMbgTargetRuntimePanel(); this.initPathPanel(); + this.initXmlPackagePanel(); this.initPostfixPanel(); - this.initPackagePanel(); this.initOptionsPanel(); this.initClearCachePanel(); - this.reset(); + this.reset(); + } + + private void initMbgTargetRuntimePanel() { + JPanel jPanel = new JPanel(); + jPanel.setLayout(new GridLayout(1, 2, 100, 0)); + + // mbgTargetRuntime + JPanel runtimePanel = new JPanel(); + runtimePanel.setLayout(new BoxLayout(runtimePanel, BoxLayout.X_AXIS)); + JLabel runtimeLabel = new JLabel("Target Runtime:"); + runtimePanel.add(runtimeLabel); + for (MbgTargetRuntimeEnum value : MbgTargetRuntimeEnum.values()) { + mbgTargetRuntimeBox.addItem(value.getName()); + } + if (StringUtils.isNotBlank(config.getGlobalConfig().getMgbTargetRuntime())) { + mbgTargetRuntimeBox.setSelectedItem(config.getGlobalConfig().getMgbTargetRuntime()); + }else { + mbgTargetRuntimeBox.setSelectedIndex(0); + } + mbgTargetRuntimeBox.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent event) { + if (Objects.equals(event.getStateChange(), ItemEvent.SELECTED)) { + // 根据当前选中的runtime 修改可供选择的client type + MbgTargetRuntimeEnum runtimeEnum = MbgTargetRuntimeEnum.getByName( + event.getItem().toString()); + List clientTypeList = MbgJavaClientConfigTypeEnum.getValuesByTargetRuntime( + runtimeEnum); + if (CollectionUtils.isNotEmpty(clientTypeList)) { + mbgJavaClientTypeBox.removeAllItems(); + for (String type : clientTypeList) { + mbgJavaClientTypeBox.addItem(type); + } + mbgJavaClientTypeBox.getParent().setVisible(true); + mbgJavaClientTypeBox.setVisible(true); + }else { + mbgJavaClientTypeBox.getParent().setVisible(false); + mbgJavaClientTypeBox.setVisible(false); + } + // MyBatis3DynamicSql & MyBatis3Kotlin 模式下没有 example 和 xml + examplePostfixPanel.setVisible(mbgJavaClientTypeBox.isVisible()); + useExampleBox.setVisible(mbgJavaClientTypeBox.isVisible()); + xmlPackageField.getParent().setVisible(mbgJavaClientTypeBox.isVisible()); + } + } + }); + runtimePanel.add(mbgTargetRuntimeBox); + jPanel.add(runtimePanel); + + // java client type + JPanel typePanel = new JPanel(); + typePanel.setLayout(new BoxLayout(typePanel, BoxLayout.X_AXIS)); + JLabel clientTypeLabel = new JLabel("Client Type:"); + typePanel.add(clientTypeLabel); + List typeList = MbgJavaClientConfigTypeEnum.getValuesByTargetRuntime( + MbgTargetRuntimeEnum.getByName(mbgTargetRuntimeBox.getSelectedItem().toString())); + if (CollectionUtils.isNotEmpty(typeList)) { + for (String type : typeList) { + mbgJavaClientTypeBox.addItem(type); + } + if (StringUtils.isNotBlank(config.getGlobalConfig().getMgbJavaClientConfigType())) { + mbgJavaClientTypeBox.setSelectedItem(config.getGlobalConfig().getMgbJavaClientConfigType()); + }else { + mbgJavaClientTypeBox.setSelectedIndex(0); + } + }else { + typePanel.setVisible(false); + mbgJavaClientTypeBox.setVisible(false); + } + typePanel.add(mbgJavaClientTypeBox); + jPanel.add(typePanel); + + TitledSeparator separator = new TitledSeparator(); + separator.setText("Runtime And Type"); + contentPanel.add(separator); + contentPanel.add(jPanel); } private void initOptionsPanel() { JBPanel optionsPanel = new JBPanel(new GridLayout(6, 2, 10, 10)); - optionsPanel.add(offsetLimitBox); optionsPanel.add(commentBox); optionsPanel.add(overrideBox); optionsPanel.add(needToStringHashcodeEqualsBox); optionsPanel.add(useSchemaPrefixBox); - optionsPanel.add(needForUpdateBox); optionsPanel.add(annotationDAOBox); optionsPanel.add(useDAOExtendStyleBox); optionsPanel.add(jsr310SupportBox); @@ -99,10 +177,10 @@ private void initOptionsPanel() { optionsPanel.add(useActualColumnNamesBox); optionsPanel.add(useTableNameAliasBox); optionsPanel.add(useExampleBox); - optionsPanel.add(mysql8Box); optionsPanel.add(lombokAnnotationBox); optionsPanel.add(lombokBuilderAnnotationBox); - optionsPanel.add(swaggerAnnotationBox); + + useExampleBox.setVisible(mbgJavaClientTypeBox.isVisible()); TitledSeparator separator = new TitledSeparator(); separator.setText("Options"); @@ -112,19 +190,9 @@ private void initOptionsPanel() { private void initPathPanel() { - JPanel sourcePathPanel = new JPanel(); - sourcePathPanel.setLayout(new BoxLayout(sourcePathPanel, BoxLayout.X_AXIS)); - JBLabel sourcePathLabel = new JBLabel("Source Path:"); - sourcePathLabel.setPreferredSize(new Dimension(200, 20)); - sourcePathPanel.add(sourcePathLabel); - sourcePathPanel.add(sourcePathField); + JPanel sourcePathPanel = buildPanel("Source Path:", sourcePathField); - JPanel resourcePathPanel = new JPanel(); - resourcePathPanel.setLayout(new BoxLayout(resourcePathPanel, BoxLayout.X_AXIS)); - JBLabel resourcePathLabel = new JBLabel("Resource Path:"); - resourcePathLabel.setPreferredSize(new Dimension(200, 20)); - resourcePathPanel.add(resourcePathLabel); - resourcePathPanel.add(resourcePathField); + JPanel resourcePathPanel = buildPanel("Resource Path:", resourcePathField); JPanel pathPanel = new JPanel(); pathPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); @@ -136,6 +204,20 @@ private void initPathPanel() { contentPanel.add(pathPanel); } + private void initXmlPackagePanel() { + + JPanel xmlPackagePanel = buildPanel("xml package:", xmlPackageField); + xmlPackagePanel.setVisible(mbgJavaClientTypeBox.isVisible()); + + JPanel packagePanel = new JPanel(); + packagePanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); + TitledSeparator separator = new TitledSeparator(); + separator.setText("Package"); + packagePanel.add(xmlPackagePanel); + contentPanel.add(separator); + contentPanel.add(packagePanel); + } + private void initClearCachePanel() { JPanel clearCachePanel = new JPanel(); @@ -162,12 +244,7 @@ private void initClearCachePanel() { private void initPostfixPanel() { - JPanel tablePrefixPanel = new JPanel(); - tablePrefixPanel.setLayout(new BoxLayout(tablePrefixPanel, BoxLayout.X_AXIS)); - JBLabel tablePrefixLabel = new JBLabel("Table Prefix:"); - tablePrefixLabel.setPreferredSize(new Dimension(200, 20)); - tablePrefixPanel.add(tablePrefixLabel); - tablePrefixPanel.add(tablePrefixField); + JPanel tablePrefixPanel = buildPanel("Table Prefix:", tablePrefixField); JPanel prefixPanel = new JPanel(); prefixPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); @@ -177,136 +254,50 @@ private void initPostfixPanel() { contentPanel.add(separator); contentPanel.add(prefixPanel); + JPanel domainPostfixPanel = buildPanel("Domain Postfix:", domainPostfixField); + JPanel mapperPostfixPanel = buildPanel("Mapper Postfix:", mapperPostfixField); + examplePostfixPanel = buildPanel("Example Postfix:", examplePostfixField); + examplePostfixPanel.setVisible(mbgJavaClientTypeBox.isVisible()); - JPanel mapperPostfixPanel = new JPanel(); - mapperPostfixPanel.setLayout(new BoxLayout(mapperPostfixPanel, BoxLayout.X_AXIS)); - JBLabel mapperPostfixLabel = new JBLabel("Mapper Postfix:"); - mapperPostfixLabel.setPreferredSize(new Dimension(200, 20)); - mapperPostfixPanel.add(mapperPostfixLabel); - mapperPostfixPanel.add(mapperPostfixField); - JPanel examplePostfixPanel = new JPanel(); - examplePostfixPanel.setLayout(new BoxLayout(examplePostfixPanel, BoxLayout.X_AXIS)); - JBLabel examplePostfixLabel = new JBLabel("Example Postfix:"); - examplePostfixLabel.setPreferredSize(new Dimension(200, 20)); - examplePostfixPanel.add(examplePostfixLabel); - examplePostfixPanel.add(examplePostfixField); JPanel postfixPanel = new JPanel(); postfixPanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); TitledSeparator separator2 = new TitledSeparator(); separator2.setText("Postfix"); + postfixPanel.add(domainPostfixPanel); postfixPanel.add(mapperPostfixPanel); postfixPanel.add(examplePostfixPanel); contentPanel.add(separator2); contentPanel.add(postfixPanel); } - private void initPackagePanel() { + private JPanel buildPanel(String text, JTextField jTextField) { + JPanel jPanel = new JPanel(); + jPanel.setLayout(new BoxLayout(jPanel, BoxLayout.X_AXIS)); + JBLabel jbLabel = new JBLabel(text); +// jbLabel.setPreferredSize(new Dimension(120, 20)); + jPanel.add(jbLabel); + jPanel.add(jTextField); + return jPanel; + } - GlobalConfig globalConfig = config.getGlobalConfig(); - JPanel projectRootPanel = new JPanel(); - projectRootPanel.setLayout(new BoxLayout(projectRootPanel, BoxLayout.X_AXIS)); - JBLabel projectRootLabel = new JBLabel("Module Root:"); - projectRootLabel.setPreferredSize(new Dimension(200, 20)); - moduleRootField.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFolderDescriptor()) { - @Override - public void actionPerformed(ActionEvent e) { - super.actionPerformed(e); - moduleRootField.setText(moduleRootField.getText().replaceAll("\\\\", "/")); - } - }); - if (globalConfig != null && !StringUtils.isEmpty(globalConfig.getModuleRootPath())) { - moduleRootField.setText(globalConfig.getModuleRootPath()); - } else { - moduleRootField.setText(project.getBasePath()); - } - projectRootPanel.add(projectRootLabel); - projectRootPanel.add(moduleRootField); - - JPanel entityPackagePanel = new JPanel(); - entityPackagePanel.setLayout(new BoxLayout(entityPackagePanel, BoxLayout.X_AXIS)); - JBLabel entityPackageLabel = new JBLabel("Domain Package:"); - entityPackageLabel.setPreferredSize(new Dimension(200, 20)); - domainPackageField = new EditorTextFieldWithBrowseButton(project, false); - domainPackageField.addActionListener(e -> { - final PackageChooserDialog chooser = new PackageChooserDialog("Select Domain Package", project); - chooser.selectPackage(domainPackageField.getText()); - chooser.show(); - final PsiPackage psiPackage = chooser.getSelectedPackage(); - String packageName = psiPackage == null ? null : psiPackage.getQualifiedName(); - domainPackageField.setText(packageName); - }); - entityPackagePanel.add(entityPackageLabel); - entityPackagePanel.add(domainPackageField); - - JPanel mapperPackagePanel = new JPanel(); - mapperPackagePanel.setLayout(new BoxLayout(mapperPackagePanel, BoxLayout.X_AXIS)); - JLabel mapperPackageLabel = new JLabel("Mapper Package:"); - mapperPackageLabel.setPreferredSize(new Dimension(200, 20)); - mapperPackageField = new EditorTextFieldWithBrowseButton(project, false); - mapperPackageField.addActionListener(e -> { - final PackageChooserDialog packageChooserDialog = new PackageChooserDialog("Select Mapper Package", project); - packageChooserDialog.selectPackage(mapperPackageField.getText()); - packageChooserDialog.show(); - final PsiPackage psiPackage = packageChooserDialog.getSelectedPackage(); - String packageName = psiPackage == null ? null : psiPackage.getQualifiedName(); - mapperPackageField.setText(packageName); - }); - mapperPackagePanel.add(mapperPackageLabel); - mapperPackagePanel.add(mapperPackageField); - - JPanel examplePackagePanel = new JPanel(); - examplePackagePanel.setLayout(new BoxLayout(examplePackagePanel, BoxLayout.X_AXIS)); - JLabel examplePackageLabel = new JLabel("Example Package:"); - examplePackageLabel.setPreferredSize(new Dimension(200, 20)); - examplePackageField = new EditorTextFieldWithBrowseButton(project, false); - examplePackageField.addActionListener(e -> { - final PackageChooserDialog packageChooserDialog = new PackageChooserDialog("Select Example Package", project); - packageChooserDialog.selectPackage(examplePackageField.getText()); - packageChooserDialog.show(); - final PsiPackage psiPackage = packageChooserDialog.getSelectedPackage(); - String packageName = psiPackage == null ? null : psiPackage.getQualifiedName(); - examplePackageField.setText(packageName); - }); - examplePackagePanel.add(examplePackageLabel); - examplePackagePanel.add(examplePackageField); + public boolean isModified() { + boolean modified = !Objects.equals(this.mbgTargetRuntimeBox.getSelectedItem(), config.getGlobalConfig().getMgbTargetRuntime()); + modified |= !Objects.equals(this.mbgJavaClientTypeBox.getSelectedItem(), config.getGlobalConfig().getMgbJavaClientConfigType()); - JPanel xmlPackagePanel = new JPanel(); - xmlPackagePanel.setLayout(new BoxLayout(xmlPackagePanel, BoxLayout.X_AXIS)); - JLabel xmlPackageLabel = new JLabel("Xml Package:"); - xmlPackageLabel.setPreferredSize(new Dimension(200, 20)); - xmlPackageField.setText(globalConfig.getXmlPackage()); - xmlPackagePanel.add(xmlPackageLabel); - xmlPackagePanel.add(xmlPackageField); + modified |= !this.sourcePathField.getText().equals(config.getGlobalConfig().getSourcePath()); + modified |= !this.resourcePathField.getText().equals(config.getGlobalConfig().getResourcePath()); - JPanel packagePanel = new JPanel(); - packagePanel.setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP)); - packagePanel.add(projectRootPanel); - packagePanel.add(entityPackagePanel); - packagePanel.add(mapperPackagePanel); - packagePanel.add(examplePackagePanel); - packagePanel.add(xmlPackagePanel); + modified |= !this.xmlPackageField.getText().equals(config.getGlobalConfig().getDefaultXmlPackage()); - TitledSeparator separator = new TitledSeparator(); - separator.setText("Package"); - contentPanel.add(separator); - contentPanel.add(packagePanel); - } + modified |= !this.tablePrefixField.getText().equals(config.getGlobalConfig().getTablePrefix()); - public boolean isModified() { - boolean modified = !this.domainPackageField.getText().equals(config.getGlobalConfig().getDomainPackage()); - modified |= !this.moduleRootField.getText().equals(config.getGlobalConfig().getModuleRootPath()); - modified |= !this.mapperPackageField.getText().equals(config.getGlobalConfig().getMapperPackage()); - modified |= !this.xmlPackageField.getText().equals(config.getGlobalConfig().getXmlPackage()); - modified |= !this.examplePackageField.getText().equals(config.getGlobalConfig().getExamplePackage()); + modified |= !this.domainPostfixField.getText().equals(config.getGlobalConfig().getDomainPostfix()); modified |= !this.mapperPostfixField.getText().equals(config.getGlobalConfig().getMapperPostfix()); modified |= !this.examplePostfixField.getText().equals(config.getGlobalConfig().getExamplePostfix()); - modified |= !this.tablePrefixField.getText().equals(config.getGlobalConfig().getTablePrefix()); - modified |= !this.sourcePathField.getText().equals(config.getGlobalConfig().getSourcePath()); - modified |= !this.resourcePathField.getText().equals(config.getGlobalConfig().getResourcePath()); - modified |= (this.offsetLimitBox.getSelectedObjects() != null) == (config.getGlobalConfig().isOffsetLimit()); + modified |= (this.commentBox.getSelectedObjects() != null) == (config.getGlobalConfig().isComment()); modified |= (this.overrideBox.getSelectedObjects() != null) == (config.getGlobalConfig().isOverride()); modified |= (this.needToStringHashcodeEqualsBox.getSelectedObjects() != null) == (config.getGlobalConfig().isNeedToStringHashcodeEquals()); @@ -317,29 +308,34 @@ public boolean isModified() { modified |= (this.useActualColumnNamesBox.getSelectedObjects() != null) == (config.getGlobalConfig().isUseActualColumnNames()); modified |= (this.useTableNameAliasBox.getSelectedObjects() != null) == (config.getGlobalConfig().isUseTableNameAlias()); modified |= (this.useExampleBox.getSelectedObjects() != null) == (config.getGlobalConfig().isUseExample()); - modified |= (this.mysql8Box.getSelectedObjects() != null) == (config.getGlobalConfig().isMysql8()); modified |= (this.lombokAnnotationBox.getSelectedObjects() != null) == (config.getGlobalConfig().isLombokAnnotation()); modified |= (this.lombokBuilderAnnotationBox.getSelectedObjects() != null) == (config.getGlobalConfig().isLombokBuilderAnnotation()); - modified |= (this.swaggerAnnotationBox.getSelectedObjects() != null) == (config.getGlobalConfig().isSwaggerAnnotation()); return modified; } public void apply() { GlobalConfig globalConfig = new GlobalConfig(); - globalConfig.setModuleRootPath(moduleRootField.getText()); + + globalConfig.setMgbTargetRuntime(mbgTargetRuntimeBox.getSelectedItem().toString()); + if (Objects.nonNull(mbgJavaClientTypeBox.getSelectedItem())) { + globalConfig.setMgbJavaClientConfigType(mbgJavaClientTypeBox.getSelectedItem().toString()); + } + + globalConfig.setSourcePath(sourcePathField.getText()); + globalConfig.setResourcePath(resourcePathField.getText()); + + globalConfig.setDefaultXmlPackage(xmlPackageField.getText()); + + globalConfig.setTablePrefix(tablePrefixField.getText()); + + globalConfig.setDomainPostfix(domainPostfixField.getText()); globalConfig.setMapperPostfix(mapperPostfixField.getText()); globalConfig.setExamplePostfix(examplePostfixField.getText()); - globalConfig.setTablePrefix(tablePrefixField.getText()); - globalConfig.setDomainPackage(domainPackageField.getText()); - globalConfig.setMapperPackage(mapperPackageField.getText()); - globalConfig.setExamplePackage(examplePackageField.getText()); - globalConfig.setXmlPackage(xmlPackageField.getText()); - globalConfig.setOffsetLimit(offsetLimitBox.getSelectedObjects() != null); + globalConfig.setComment(commentBox.getSelectedObjects() != null); globalConfig.setOverride(overrideBox.getSelectedObjects() != null); globalConfig.setNeedToStringHashcodeEquals(needToStringHashcodeEqualsBox.getSelectedObjects() != null); globalConfig.setUseSchemaPrefix(useSchemaPrefixBox.getSelectedObjects() != null); - globalConfig.setNeedForUpdate(needForUpdateBox.getSelectedObjects() != null); globalConfig.setAnnotationDAO(annotationDAOBox.getSelectedObjects() != null); globalConfig.setUseDAOExtendStyle(useDAOExtendStyleBox.getSelectedObjects() != null); globalConfig.setJsr310Support(jsr310SupportBox.getSelectedObjects() != null); @@ -347,50 +343,41 @@ public void apply() { globalConfig.setUseActualColumnNames(useActualColumnNamesBox.getSelectedObjects() != null); globalConfig.setUseTableNameAlias(useTableNameAliasBox.getSelectedObjects() != null); globalConfig.setUseExample(useExampleBox.getSelectedObjects() != null); - globalConfig.setMysql8(mysql8Box.getSelectedObjects() != null); globalConfig.setLombokAnnotation(lombokAnnotationBox.getSelectedObjects() != null); globalConfig.setLombokBuilderAnnotation(lombokBuilderAnnotationBox.getSelectedObjects() != null); - globalConfig.setSwaggerAnnotation(swaggerAnnotationBox.getSelectedObjects() != null); - - globalConfig.setSourcePath(sourcePathField.getText()); - globalConfig.setResourcePath(resourcePathField.getText()); this.config.setGlobalConfig(globalConfig); - - } public void reset() { GlobalConfig globalConfig = config.getGlobalConfig(); - mapperPostfixField.setText(globalConfig.getMapperPostfix()); - examplePostfixField.setText(globalConfig.getExamplePostfix()); - tablePrefixField.setText(globalConfig.getTablePrefix()); - domainPackageField.setText(globalConfig.getDomainPackage()); - mapperPackageField.setText(globalConfig.getMapperPackage()); - examplePackageField.setText(globalConfig.getExamplePackage()); - xmlPackageField.setText(globalConfig.getXmlPackage()); + + mbgTargetRuntimeBox.setSelectedItem(globalConfig.getMgbTargetRuntime()); + mbgJavaClientTypeBox.setSelectedItem(globalConfig.getMgbJavaClientConfigType()); sourcePathField.setText(globalConfig.getSourcePath()); resourcePathField.setText(globalConfig.getResourcePath()); - offsetLimitBox.setSelected(globalConfig.isOffsetLimit()); + xmlPackageField.setText(globalConfig.getDefaultXmlPackage()); + + tablePrefixField.setText(globalConfig.getTablePrefix()); + + domainPostfixField.setText(globalConfig.getDomainPostfix()); + mapperPostfixField.setText(globalConfig.getMapperPostfix()); + examplePostfixField.setText(globalConfig.getExamplePostfix()); + commentBox.setSelected(globalConfig.isComment()); overrideBox.setSelected(globalConfig.isOverride()); needToStringHashcodeEqualsBox.setSelected(globalConfig.isNeedToStringHashcodeEquals()); useSchemaPrefixBox.setSelected(globalConfig.isUseSchemaPrefix()); - needForUpdateBox.setSelected(globalConfig.isNeedForUpdate()); annotationDAOBox.setSelected(globalConfig.isAnnotationDAO()); useDAOExtendStyleBox.setSelected(globalConfig.isUseDAOExtendStyle()); jsr310SupportBox.setSelected(globalConfig.isJsr310Support()); annotationBox.setSelected(globalConfig.isAnnotation()); useActualColumnNamesBox.setSelected(globalConfig.isUseActualColumnNames()); - useTableNameAliasBox.setSelected(globalConfig.isUseTableNameAlias()); useExampleBox.setSelected(globalConfig.isUseExample()); - mysql8Box.setSelected(globalConfig.isMysql8()); lombokAnnotationBox.setSelected(globalConfig.isLombokAnnotation()); lombokBuilderAnnotationBox.setSelected(globalConfig.isLombokBuilderAnnotation()); - swaggerAnnotationBox.setSelected(globalConfig.isSwaggerAnnotation()); - } @Override diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/util/JavaFileMerger.java b/src/com/github/leecho/idea/plugin/mybatis/generator/util/JavaFileMerger.java deleted file mode 100644 index 5eeb0f3..0000000 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/util/JavaFileMerger.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.github.leecho.idea.plugin.mybatis.generator.util; - -import com.github.javaparser.JavaParser; -import com.github.javaparser.ast.CompilationUnit; -import com.github.javaparser.ast.ImportDeclaration; -import com.github.javaparser.ast.Node; -import com.github.javaparser.ast.NodeList; -import com.github.javaparser.ast.body.MethodDeclaration; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.stream.Collectors; - -/** - * @author LIQIU - */ -public class JavaFileMerger { - - public String getNewJavaFile(String newFileSource, String existingFileFullPath) throws FileNotFoundException { - CompilationUnit newCompilationUnit = JavaParser.parse(newFileSource); - CompilationUnit existingCompilationUnit = JavaParser.parse(new File(existingFileFullPath)); - return mergerFile(newCompilationUnit, existingCompilationUnit, newFileSource); - } - - public String mergerFile(CompilationUnit newCompilationUnit, CompilationUnit existingCompilationUnit, String newFileSource) { - - NodeList newsImports = newCompilationUnit.getImports(); - NodeList existsImports = existingCompilationUnit.getImports(); - HashSet allImports = new HashSet<>(); - allImports.addAll(newsImports); - allImports.addAll(existsImports); - allImports.removeAll(newsImports); - - List sources = Arrays.stream(newFileSource.split("\n")).collect(Collectors.toList()); - - sources.addAll(newsImports.size() + 2, allImports.stream().map(importDeclaration -> importDeclaration.toString().replace("\r\n","")).collect(Collectors.toList())); - - - List newMethods = newCompilationUnit.getTypes().get(0).getMethods(); - List oldMethods = existingCompilationUnit.getTypes().get(0).getMethods(); - HashSet allMethods = new HashSet<>(); - allMethods.addAll(newMethods); - allMethods.addAll(oldMethods); - allMethods.removeAll(newMethods); - - sources.addAll(sources.size() - 1, allMethods.stream().map(methodDeclaration -> "\n" + " " + methodDeclaration.toString()).collect(Collectors.toList())); - return String.join("\n", sources); - } -} diff --git a/src/com/github/leecho/idea/plugin/mybatis/generator/util/XmlFileMerger.java b/src/com/github/leecho/idea/plugin/mybatis/generator/util/XmlFileMerger.java deleted file mode 100644 index 44a746c..0000000 --- a/src/com/github/leecho/idea/plugin/mybatis/generator/util/XmlFileMerger.java +++ /dev/null @@ -1,256 +0,0 @@ -package com.github.leecho.idea.plugin.mybatis.generator.util; - -import static org.mybatis.generator.internal.util.messages.Messages.getString; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import com.sun.org.apache.xerces.internal.dom.DeferredTextImpl; -import org.mybatis.generator.api.GeneratedXmlFile; -import org.mybatis.generator.config.MergeConstants; -import org.mybatis.generator.exception.ShellException; -import org.mybatis.generator.internal.DomWriter; -import org.w3c.dom.Comment; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentType; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.Text; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * This class handles the task of merging changes into an existing XML file. - * - * @author Jeff Butler - */ -public class XmlFileMerger { - private static class NullEntityResolver implements EntityResolver { - /** - * returns an empty reader. This is done so that the parser doesn't - * attempt to read a DTD. We don't need that support for the merge and - * it can cause problems on systems that aren't Internet connected. - */ - @Override - public InputSource resolveEntity(String publicId, String systemId) - throws SAXException, IOException { - - StringReader sr = new StringReader(""); //$NON-NLS-1$ - - return new InputSource(sr); - } - } - - /** - * Utility class - no instances allowed - */ - private XmlFileMerger() { - super(); - } - - public static String getMergedSource(GeneratedXmlFile generatedXmlFile, - File existingFile) throws ShellException { - - try { - return getMergedSource(new InputSource(new StringReader(generatedXmlFile.getFormattedContent())), - new InputSource(new InputStreamReader(new FileInputStream(existingFile), "UTF-8")), //$NON-NLS-1$ - existingFile.getName()); - } catch (IOException e) { - throw new ShellException(getString("Warning.13", //$NON-NLS-1$ - existingFile.getName()), e); - } catch (SAXException e) { - throw new ShellException(getString("Warning.13", //$NON-NLS-1$ - existingFile.getName()), e); - } catch (ParserConfigurationException e) { - throw new ShellException(getString("Warning.13", //$NON-NLS-1$ - existingFile.getName()), e); - } - } - - public static String getMergedSource(InputSource newFile, - InputSource existingFile, String existingFileName) throws IOException, SAXException, - ParserConfigurationException, ShellException { - - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - factory.setExpandEntityReferences(false); - DocumentBuilder builder = factory.newDocumentBuilder(); - builder.setEntityResolver(new NullEntityResolver()); - - Document existingDocument = builder.parse(existingFile); - Document newDocument = builder.parse(newFile); - - DocumentType newDocType = newDocument.getDoctype(); - DocumentType existingDocType = existingDocument.getDoctype(); - - if (!newDocType.getName().equals(existingDocType.getName())) { - throw new ShellException(getString("Warning.12", //$NON-NLS-1$ - existingFileName)); - } - - Element existingRootElement = existingDocument.getDocumentElement(); - Element newRootElement = newDocument.getDocumentElement(); - - // reconcile the root element attributes - - // take all attributes from the new element and add to the existing - // element - - // remove all attributes from the existing root element - NamedNodeMap attributes = existingRootElement.getAttributes(); - int attributeCount = attributes.getLength(); - for (int i = attributeCount - 1; i >= 0; i--) { - Node node = attributes.item(i); - existingRootElement.removeAttribute(node.getNodeName()); - } - - // add attributes from the new root node to the old root node - attributes = newRootElement.getAttributes(); - attributeCount = attributes.getLength(); - for (int i = 0; i < attributeCount; i++) { - Node node = attributes.item(i); - existingRootElement.setAttribute(node.getNodeName(), node - .getNodeValue()); - } - - NodeList newMethods = newRootElement.getChildNodes(); - List methods = new ArrayList(); - for (int i = 0; i < newMethods.getLength(); i++) { - Node node = newMethods.item(i); - try { - if (node instanceof DeferredTextImpl) { - continue; - } - Element ele = (Element) node; - methods.add(ele.getAttribute("id")); - } catch (Exception e) { - //#text节点转换会异常 - continue; - } - if (i == newMethods.getLength() - 1) { - if (isWhiteSpace(node)) { - break; - } - } - } - - // remove the old generated elements and any - // white space before the old nodes - List nodesToDelete = new ArrayList(); - NodeList children = existingRootElement.getChildNodes(); - int length = children.getLength(); - for (int i = 0; i < length; i++) { - Node node = children.item(i); - if (isGeneratedNode(node, methods)) { - nodesToDelete.add(node); - } else if (isWhiteSpace(node) - && isGeneratedNode(children.item(i + 1), methods)) { - nodesToDelete.add(node); - } - } - - for (Node node : nodesToDelete) { - existingRootElement.removeChild(node); - } - - // add the new generated elements - children = newRootElement.getChildNodes(); - length = children.getLength(); - Node firstChild = existingRootElement.getFirstChild(); - for (int i = 0; i < length; i++) { - Node node = children.item(i); - // don't add the last node if it is only white space - if (i == length - 1 && isWhiteSpace(node)) { - break; - } - - Node newNode = existingDocument.importNode(node, true); - if (firstChild == null) { - existingRootElement.appendChild(newNode); - } else { - existingRootElement.insertBefore(newNode, firstChild); - } - } - - // pretty print the result - return prettyPrint(existingDocument); - } - - private static String prettyPrint(Document document) throws ShellException { - DomWriter dw = new DomWriter(); - String s = dw.toString(document); - return s; - } - - private static boolean isGeneratedNode(Node node, List methods) { - boolean rc = false; - - if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { - Element element = (Element) node; - String id = element.getAttribute("id"); //$NON-NLS-1$ - if (methods.contains(id)) { - return true; - } - if (id != null) { - for (String prefix : MergeConstants.OLD_XML_ELEMENT_PREFIXES) { - if (id.startsWith(prefix)) { - rc = true; - break; - } - } - } - - if (rc == false) { - // check for new node format - if the first non-whitespace node - // is an XML comment, and the comment includes - // one of the old element tags, - // then it is a generated node - NodeList children = node.getChildNodes(); - int length = children.getLength(); - for (int i = 0; i < length; i++) { - Node childNode = children.item(i); - if (isWhiteSpace(childNode)) { - continue; - } else if (childNode.getNodeType() == Node.COMMENT_NODE) { - Comment comment = (Comment) childNode; - String commentData = comment.getData(); - for (String tag : MergeConstants.OLD_ELEMENT_TAGS) { - if (commentData.contains(tag)) { - rc = true; - break; - } - } - } else { - break; - } - } - } - } - - return rc; - } - - private static boolean isWhiteSpace(Node node) { - boolean rc = false; - - if (node != null && node.getNodeType() == Node.TEXT_NODE) { - Text tn = (Text) node; - if (tn.getData().trim().length() == 0) { - rc = true; - } - } - - return rc; - } -} \ No newline at end of file