├── .idea
├── encodings.xml
├── libraries
│ └── gene_plugin_1_0_SNAPSHOT.xml
├── misc.xml
├── modules.xml
├── vcs.xml
└── workspace.xml
├── README.md
├── better-mybatis-generator.iml
├── better-mybatis-generator.zip
├── image
├── 1.png
├── 2.png
├── 3.png
├── 4.png
├── 5.png
├── 6.png
├── 7.png
├── 8.png
├── mysql8-config.png
├── mysql选项.png
├── run.png
├── 从github创建工程.png
└── 修改插件sdk.png
├── lib
├── gene-plugin-1.0-SNAPSHOT.jar
├── mariadb-java-client-2.3.0.jar
├── mybatis-generator-core-1.3.5.jar
├── mysql-connector-java-5.1.38.jar
├── mysql-connector-java-8.0.11.jar
├── ojdbc14.jar
├── postgresql-9.4.1209.jar
├── sqlite-jdbc-3.19.3.jar
└── sqljdbc4-4.0.jar
├── resources
└── META-INF
│ └── plugin.xml
└── src
└── cn
└── kt
├── action
└── MainAction.java
├── generate
└── Generate.java
├── model
├── Config.java
├── DbType.java
├── TableInfo.java
└── User.java
├── setting
├── PersistentConfig.java
└── SettingConfigurable.java
├── ui
├── MainUI.java
├── SettingUI.java
└── UserUI.java
└── util
├── GeneratorCallback.java
├── JTextFieldHintListener.java
└── StringUtils.java
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/libraries/gene_plugin_1_0_SNAPSHOT.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | better-mybatis-generator idea plugin
2 | ====
3 | 插件功能:在idea的database工具中使用,选择表(一或n,建议n小于10),生成mybatis相关的代码,(包括:dao、example、domain、xml)。
4 | Use in idea database tool,right click table(one or more) to generate mybatis files (include:dao、example、domain、xml).
5 |
6 | Plugin Installation:
7 | -------
8 | - 在idea插件系统里安装 | Using IDE built-in plugin system on Windows:
9 | - File > Settings > Plugins > Browse repositories... > Search for "better-mybatis-generator" > Install Plugin
10 | - 手动zip安装 | Manually:
11 | - Download the [latest release](https://plugins.jetbrains.com/plugin/11021-better-mybatis-generator) and install it manually using Preferences > Plugins > Install plugin from disk...
12 |
13 | Using sample screenshots:
14 | -------
15 | #1、设置自定义默认配置,若不设置,则使用程序默认配置。 | Set custom default configuration,If not, use the program default configuration.
16 | 
17 |
18 | #2、配置数据库 | Connecting to Your Database.
19 | 
20 | 
21 | 
22 |
23 | #3、在需要生成代码的表上右键,选择mybatis generate,打开预览界面。 | Select one or more tables,right click and select mybatis generate to open generatoe main UI.
24 | 
25 |
26 | #4、设置确认完成后,点击ok,开始生产代码。 | Check configuration in main ui,click ok.
27 | 
28 |
29 | #5、首次使用此插件,需要为插件提供数据库账号密码。 | Provide account and password for the first time.
30 | 
31 |
32 | #6、检查生成的代码文件 | Generate work finish,Check your files.
33 | 
34 |
35 |
36 | 如何在本地运行/调试此插件 | How to run/debug plugin :
37 | -------
38 | #1、创建工程 File -> New -> Project from Version Control -> Git 填写github地址:https://github.com/kmaster/better-mybatis-generator.git
39 | 
40 | #2、修改sdk
41 | 
42 | #3、运行配置无误则直接run/debug。若因idea版本导致提供的配置不对,请考虑本地创建空的插件工程然后参考其配置。
43 | 
44 | 此时打上断点就可以一步步调试,修改代码后点击 Build->prepare plugin modle "xxx" For Deployment生成插件安装包再本地安装使用,
45 | 如果想优化此插件代码,比如其他数据库或运行环境,可以修改后在github上发起pull request。能点个star就更好了,哈哈。
46 |
47 | 注意事项 | notice:
48 | -------
49 | #1、当数据库用mysql8,在URL上定义时区,推荐使用'?serverTimezone=GMT',配置中勾选上mysql8选项。 | If your database is mysql8,please add '?serverTimezone=GMT' and select mysql8 option
50 | 
51 | 
52 |
53 |
54 |
--------------------------------------------------------------------------------
/better-mybatis-generator.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/better-mybatis-generator.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/better-mybatis-generator.zip
--------------------------------------------------------------------------------
/image/1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/1.png
--------------------------------------------------------------------------------
/image/2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/2.png
--------------------------------------------------------------------------------
/image/3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/3.png
--------------------------------------------------------------------------------
/image/4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/4.png
--------------------------------------------------------------------------------
/image/5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/5.png
--------------------------------------------------------------------------------
/image/6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/6.png
--------------------------------------------------------------------------------
/image/7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/7.png
--------------------------------------------------------------------------------
/image/8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/8.png
--------------------------------------------------------------------------------
/image/mysql8-config.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/mysql8-config.png
--------------------------------------------------------------------------------
/image/mysql选项.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/mysql选项.png
--------------------------------------------------------------------------------
/image/run.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/run.png
--------------------------------------------------------------------------------
/image/从github创建工程.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/从github创建工程.png
--------------------------------------------------------------------------------
/image/修改插件sdk.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/image/修改插件sdk.png
--------------------------------------------------------------------------------
/lib/gene-plugin-1.0-SNAPSHOT.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/gene-plugin-1.0-SNAPSHOT.jar
--------------------------------------------------------------------------------
/lib/mariadb-java-client-2.3.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/mariadb-java-client-2.3.0.jar
--------------------------------------------------------------------------------
/lib/mybatis-generator-core-1.3.5.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/mybatis-generator-core-1.3.5.jar
--------------------------------------------------------------------------------
/lib/mysql-connector-java-5.1.38.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/mysql-connector-java-5.1.38.jar
--------------------------------------------------------------------------------
/lib/mysql-connector-java-8.0.11.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/mysql-connector-java-8.0.11.jar
--------------------------------------------------------------------------------
/lib/ojdbc14.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/ojdbc14.jar
--------------------------------------------------------------------------------
/lib/postgresql-9.4.1209.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/postgresql-9.4.1209.jar
--------------------------------------------------------------------------------
/lib/sqlite-jdbc-3.19.3.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/sqlite-jdbc-3.19.3.jar
--------------------------------------------------------------------------------
/lib/sqljdbc4-4.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kmaster/better-mybatis-generator/4b5ff4e203642e8e48fe455b73147df50388c449/lib/sqljdbc4-4.0.jar
--------------------------------------------------------------------------------
/resources/META-INF/plugin.xml:
--------------------------------------------------------------------------------
1 |
2 | cn.kt.better.mybatis.generator.id
3 | better-mybatis-generator
4 | 1.5.5
5 | kang tian
6 |
7 |
8 |
11 | 插件功能:在idea的database工具中使用,选择表,生成mybatis相关的代码。已支持的数据库:Mysql、Mysql8、Oracle、MariaDB。待验证:PostgreSQL与SQL Server
12 | Step1: 连接Database: View > Tool Windows > Database 。
13 | Step2: 选择表(一或n,建议n小于10),右击 选择 mybatis generate 打开插件主页。
14 | Step3: 填写配置,检查无误后点击 ok 。
15 | Step4: 首次使用时请提供账号密码。
16 | Step5: 检查、使用生成的代码。
17 | Setting: Tools > MyBatis generator Plugin 此处设置默认配置,未设置则使用程序默认配置。
18 | 更多的插件使用截图和注意事项见: 插件使用介绍
19 |
20 |
21 |
22 | Function: Use in idea database tool,right click table to generate mybatis files (include:dao、example、domain、xml).Currently supported databases: Mysql,Mysql8, Oracle. To be verified: Postgre SQL and SQL Server
23 | Step1: Connecting to Your Database: View > Tool Windows > Database .
24 | Step2: Select tables(one or N,recommend N less than 10),Right Click and select mybatis generate to open generator main UI.
25 | Step3: Check configuration in main ui,click ok .
26 | Step4: Provide account and password for the first time.
27 | Step5: Generate work finish,check files and it can be use.
28 | Setting: Tools > MyBatis generator Plugin set custom default configuration,If not, use the program default configuration.
29 | More tutorial please visit here
30 |
31 | ]]>
32 |
33 |
34 |
35 |
36 |
38 | v1.5.5
39 | 用后台任务执行代码生成任务,在状态栏显示进度,去掉结束后的确认界面以解决多表生成时的不断确认问题。
40 | Execute the code generation task with the background task, display the progress in the status bar,
41 | and remove the confirmation interface after the end to solve the continuous confirmation problem when the multi-table is generated.
42 |
43 | v1.5.4
44 | 在使用mysql8时,需要在数据库连接url上添加'?serverTimezone=GMT' 并在生成配置中勾选上mysql8选项。
45 | When connecting mysql8,add '?serverTimezone=GMT' at URL.
46 |
47 | v1.5
48 | Support for IDEA the latest version.
49 | Optimize Mysql8 database connection.
50 | Add MariaDB support
51 |
52 | v1.4
53 | Fixed errors in oracle connection failures and code generation failures.
54 |
55 | v1.3
56 | Reduced version requirements, Change Message and Options description to English.
57 |
58 | v1.0
59 | Initial release of the plugin.
60 | Provide mybatis Generate function according to configuration and default configuration in setting.
61 |
62 |
63 | ]]>
64 |
65 |
66 |
67 |
68 | com.intellij.database
69 |
70 |
72 |
74 |
75 |
76 |
77 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/src/cn/kt/action/MainAction.java:
--------------------------------------------------------------------------------
1 | package cn.kt.action;
2 |
3 | import cn.kt.ui.MainUI;
4 | import com.intellij.database.psi.DbTable;
5 | import com.intellij.openapi.actionSystem.AnAction;
6 | import com.intellij.openapi.actionSystem.AnActionEvent;
7 | import com.intellij.openapi.actionSystem.LangDataKeys;
8 | import com.intellij.openapi.ui.Messages;
9 | import com.intellij.psi.PsiElement;
10 |
11 | /**
12 | * mybatis generator工具生成类
13 | * Created by kangtian on 2018/7/17.
14 | */
15 | public class MainAction extends AnAction {
16 |
17 |
18 | /**
19 | * 点击后打开插件主页面
20 | * @param e
21 | */
22 | @Override
23 | public void actionPerformed(AnActionEvent e) {
24 | PsiElement[] psiElements = e.getData(LangDataKeys.PSI_ELEMENT_ARRAY);
25 | if (psiElements == null || psiElements.length == 0) {
26 | Messages.showMessageDialog("Please select one or more tables", "Notice", Messages.getInformationIcon());
27 | return;
28 | }
29 | for (PsiElement psiElement : psiElements) {
30 | if (!(psiElement instanceof DbTable)) {
31 | Messages.showMessageDialog("Please select one or more tables", "Notice", Messages.getInformationIcon());
32 | return;
33 | }
34 | }
35 | new MainUI(e);
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/src/cn/kt/generate/Generate.java:
--------------------------------------------------------------------------------
1 | package cn.kt.generate;
2 |
3 | import cn.kt.DbRemarksCommentGenerator;
4 | import cn.kt.model.Config;
5 | import cn.kt.model.DbType;
6 | import cn.kt.model.User;
7 | import cn.kt.setting.PersistentConfig;
8 | import cn.kt.ui.UserUI;
9 | import cn.kt.util.GeneratorCallback;
10 | import cn.kt.util.StringUtils;
11 | import com.intellij.credentialStore.CredentialAttributes;
12 | import com.intellij.database.model.RawConnectionConfig;
13 | import com.intellij.database.psi.DbDataSource;
14 | import com.intellij.database.psi.DbTable;
15 | import com.intellij.ide.passwordSafe.PasswordSafe;
16 | import com.intellij.openapi.actionSystem.AnActionEvent;
17 | import com.intellij.openapi.actionSystem.LangDataKeys;
18 | import com.intellij.openapi.actionSystem.PlatformDataKeys;
19 | import com.intellij.openapi.application.ApplicationManager;
20 | import com.intellij.openapi.progress.ProgressIndicator;
21 | import com.intellij.openapi.progress.ProgressManager;
22 | import com.intellij.openapi.progress.Task;
23 | import com.intellij.openapi.project.Project;
24 | import com.intellij.psi.PsiElement;
25 | import org.jetbrains.annotations.NotNull;
26 | import org.mybatis.generator.api.MyBatisGenerator;
27 | import org.mybatis.generator.api.ShellCallback;
28 | import org.mybatis.generator.config.*;
29 | import org.mybatis.generator.internal.DefaultShellCallback;
30 |
31 | import java.io.File;
32 | import java.util.*;
33 |
34 | /**
35 | * 生成mybatis相关代码
36 | * Created by kangtian on 2018/7/28.
37 | */
38 | public class Generate {
39 |
40 | private AnActionEvent anActionEvent;
41 | private Project project;
42 | private PersistentConfig persistentConfig;//持久化的配置
43 | private Config config;//界面默认配置
44 | private String username;
45 | private String DatabaseType;//数据库类型
46 | private String driverClass;//数据库驱动
47 | private String url;//数据库连接url
48 |
49 | public Generate(Config config) {
50 | this.config = config;
51 | }
52 |
53 | /**
54 | * 自动生成的主逻辑
55 | *
56 | * @param anActionEvent
57 | * @throws Exception
58 | */
59 | public void execute(AnActionEvent anActionEvent) throws Exception {
60 | this.anActionEvent = anActionEvent;
61 | this.project = anActionEvent.getData(PlatformDataKeys.PROJECT);
62 | this.persistentConfig = PersistentConfig.getInstance(project);
63 |
64 | saveConfig();//执行前 先保存一份当前配置
65 |
66 | PsiElement[] psiElements = anActionEvent.getData(LangDataKeys.PSI_ELEMENT_ARRAY);
67 |
68 | if (psiElements == null || psiElements.length == 0) {
69 | return;
70 | }
71 |
72 | RawConnectionConfig connectionConfig = ((DbDataSource) psiElements[0].getParent().getParent()).getConnectionConfig();
73 | driverClass = connectionConfig.getDriverClass();
74 | url = connectionConfig.getUrl();
75 | if (driverClass.contains("mysql")) {
76 | DatabaseType = "MySQL";
77 | } else if (driverClass.contains("oracle")) {
78 | DatabaseType = "Oracle";
79 | } else if (driverClass.contains("postgresql")) {
80 | DatabaseType = "PostgreSQL";
81 | } else if (driverClass.contains("sqlserver")) {
82 | DatabaseType = "SqlServer";
83 | } else if (driverClass.contains("sqlite")) {
84 | DatabaseType = "Sqlite";
85 | } else if (driverClass.contains("mariadb")) {
86 | DatabaseType = "MariaDB";
87 | }
88 |
89 |
90 | //用后台任务执行代码生成
91 | ApplicationManager.getApplication().invokeLater(new Runnable() {
92 | @Override
93 | public void run() {
94 | ProgressManager.getInstance().run(new Task.Backgroundable(project, "mybatis generating...") {
95 | @Override
96 | public void run(@NotNull ProgressIndicator indicator) {
97 |
98 | for (PsiElement psiElement : psiElements) {
99 | if (!(psiElement instanceof DbTable)) {
100 | continue;
101 | }
102 | Configuration configuration = new Configuration();
103 | Context context = new Context(ModelType.CONDITIONAL);
104 | configuration.addContext(context);
105 |
106 | context.setId("myid");
107 | context.addProperty("autoDelimitKeywords", "true");
108 | context.addProperty("beginningDelimiter", "`");
109 | context.addProperty("endingDelimiter", "`");
110 | context.addProperty("javaFileEncoding", "UTF-8");
111 | context.addProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING, "UTF-8");
112 | context.setTargetRuntime("MyBatis3");
113 |
114 | JDBCConnectionConfiguration jdbcConfig = buildJdbcConfig(psiElement);
115 | if (jdbcConfig == null) {
116 | return;
117 | }
118 | TableConfiguration tableConfig = buildTableConfig(psiElement, context);
119 | JavaModelGeneratorConfiguration modelConfig = buildModelConfig();
120 | SqlMapGeneratorConfiguration mapperConfig = buildMapperXmlConfig();
121 | JavaClientGeneratorConfiguration daoConfig = buildDaoConfig();
122 | CommentGeneratorConfiguration commentConfig = buildCommentConfig();
123 |
124 | context.addTableConfiguration(tableConfig);
125 | context.setJdbcConnectionConfiguration(jdbcConfig);
126 | context.setJavaModelGeneratorConfiguration(modelConfig);
127 | context.setSqlMapGeneratorConfiguration(mapperConfig);
128 | context.setJavaClientGeneratorConfiguration(daoConfig);
129 | context.setCommentGeneratorConfiguration(commentConfig);
130 | addPluginConfiguration(psiElement, context);
131 |
132 | createFolderForNeed(config);
133 | List warnings = new ArrayList<>();
134 | ShellCallback shellCallback = new DefaultShellCallback(true); // override=true
135 | Set fullyqualifiedTables = new HashSet<>();
136 | Set contexts = new HashSet<>();
137 | try {
138 | MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, shellCallback, warnings);
139 | myBatisGenerator.generate(new GeneratorCallback(), contexts, fullyqualifiedTables);
140 | } catch (Exception e) {
141 | // Messages.showMessageDialog(e.getMessage() + " if use mysql,check version8?", "Generate failure", Messages.getInformationIcon());
142 | System.out.println("代码生成报错");
143 |
144 | }
145 | project.getBaseDir().refresh(false, true);
146 | }
147 | }
148 | });
149 | }
150 | });
151 |
152 |
153 | }
154 |
155 | /**
156 | * 创建所需目录
157 | *
158 | * @param config
159 | */
160 | private void createFolderForNeed(Config config) {
161 | String modelTargetFolder = config.getModelTargetFolder();
162 | String daoTargetFolder = config.getDaoTargetFolder();
163 | String xmlTargetFolder = config.getXmlTargetFolder();
164 |
165 | String modelMvnPath = config.getModelMvnPath();
166 | String daoMvnPath = config.getDaoMvnPath();
167 | String xmlMvnPath = config.getXmlMvnPath();
168 |
169 | String modelPath = modelTargetFolder + "/" + modelMvnPath + "/";
170 | String daoPath = daoTargetFolder + "/" + daoMvnPath + "/";
171 | String xmlPath = xmlTargetFolder + "/" + xmlMvnPath + "/";
172 |
173 | File modelFile = new File(modelPath);
174 | if (!modelFile.exists() && !modelFile.isDirectory()) {
175 | modelFile.mkdirs();
176 | }
177 |
178 | File daoFile = new File(daoPath);
179 | if (!daoFile.exists() && !daoFile.isDirectory()) {
180 | daoFile.mkdirs();
181 | }
182 |
183 | File xmlFile = new File(xmlPath);
184 | if (!xmlFile.exists() && !xmlFile.isDirectory()) {
185 | xmlFile.mkdirs();
186 | }
187 |
188 | }
189 |
190 |
191 | /**
192 | * 保存当前配置到历史记录
193 | */
194 | private void saveConfig() {
195 | Map historyConfigList = persistentConfig.getHistoryConfigList();
196 | if (historyConfigList == null) {
197 | historyConfigList = new HashMap<>();
198 | }
199 |
200 | String daoName = config.getDaoName();
201 | String modelName = config.getModelName();
202 | String daoPostfix = daoName.replace(modelName, "");
203 | config.setDaoPostfix(daoPostfix);
204 |
205 | historyConfigList.put(config.getName(), config);
206 | persistentConfig.setHistoryConfigList(historyConfigList);
207 |
208 | }
209 |
210 | /**
211 | * 生成数据库连接配置
212 | *
213 | * @param psiElement
214 | * @return
215 | */
216 | private JDBCConnectionConfiguration buildJdbcConfig(PsiElement psiElement) {
217 |
218 | JDBCConnectionConfiguration jdbcConfig = new JDBCConnectionConfiguration();
219 | jdbcConfig.addProperty("nullCatalogMeansCurrent", "true");
220 |
221 |
222 | Map users = persistentConfig.getUsers();
223 | if (users != null && users.containsKey(url)) {
224 | User user = users.get(url);
225 |
226 | username = user.getUsername();
227 |
228 | CredentialAttributes attributes_get = new CredentialAttributes("better-mybatis-generator-" + url, username, this.getClass(), false);
229 | String password = PasswordSafe.getInstance().getPassword(attributes_get);
230 | if (StringUtils.isEmpty(password)) {
231 | new UserUI(driverClass, url, anActionEvent, config);
232 | return null;
233 | }
234 |
235 | jdbcConfig.setUserId(username);
236 | jdbcConfig.setPassword(password);
237 |
238 | Boolean mySQL_8 = config.isMysql_8();
239 | if (mySQL_8) {
240 | driverClass = DbType.MySQL_8.getDriverClass();
241 | }
242 |
243 | jdbcConfig.setDriverClass(driverClass);
244 | jdbcConfig.setConnectionURL(url);
245 | return jdbcConfig;
246 | } else {
247 | new UserUI(driverClass, url, anActionEvent, config);
248 | return null;
249 | }
250 |
251 | }
252 |
253 | /**
254 | * 生成table配置
255 | *
256 | * @param psiElement
257 | * @param context
258 | * @return
259 | */
260 | private TableConfiguration buildTableConfig(PsiElement psiElement, Context context) {
261 | TableConfiguration tableConfig = new TableConfiguration(context);
262 | tableConfig.setTableName(config.getTableName());
263 | tableConfig.setDomainObjectName(config.getModelName());
264 |
265 | String schema;
266 | if (DatabaseType.equals(DbType.MySQL.name())) {
267 | String[] name_split = url.split("/");
268 | schema = name_split[name_split.length - 1];
269 | tableConfig.setSchema(schema);
270 | } else if (DatabaseType.equals(DbType.Oracle.name())) {
271 | String[] name_split = url.split(":");
272 | schema = name_split[name_split.length - 1];
273 | tableConfig.setCatalog(schema);
274 | } else {
275 | String[] name_split = url.split("/");
276 | schema = name_split[name_split.length - 1];
277 | tableConfig.setCatalog(schema);
278 | }
279 |
280 | if (!config.isUseExample()) {
281 | tableConfig.setUpdateByExampleStatementEnabled(false);
282 | tableConfig.setCountByExampleStatementEnabled(false);
283 | tableConfig.setDeleteByExampleStatementEnabled(false);
284 | tableConfig.setSelectByExampleStatementEnabled(false);
285 | }
286 | if (config.isUseSchemaPrefix()) {
287 | if (DbType.MySQL.name().equals(DatabaseType)) {
288 | tableConfig.setSchema(schema);
289 | } else if (DbType.Oracle.name().equals(DatabaseType)) {
290 | //Oracle的schema为用户名,如果连接用户拥有dba等高级权限,若不设schema,会导致把其他用户下同名的表也生成一遍导致mapper中代码重复
291 | tableConfig.setSchema(username);
292 | } else {
293 | tableConfig.setCatalog(schema);
294 | }
295 | }
296 |
297 | if ("org.postgresql.Driver".equals(driverClass)) {
298 | tableConfig.setDelimitIdentifiers(true);
299 | }
300 |
301 | if (!StringUtils.isEmpty(config.getPrimaryKey())) {
302 | String dbType = DatabaseType;
303 | if (DbType.MySQL.name().equals(DatabaseType)) {
304 | dbType = "JDBC";
305 | //dbType为JDBC,且配置中开启useGeneratedKeys时,Mybatis会使用Jdbc3KeyGenerator,
306 | //使用该KeyGenerator的好处就是直接在一次INSERT 语句内,通过resultSet获取得到 生成的主键值,
307 | //并很好的支持设置了读写分离代理的数据库
308 | //例如阿里云RDS + 读写分离代理 无需指定主库
309 | //当使用SelectKey时,Mybatis会使用SelectKeyGenerator,INSERT之后,多发送一次查询语句,获得主键值
310 | //在上述读写分离被代理的情况下,会得不到正确的主键
311 | }
312 | tableConfig.setGeneratedKey(new GeneratedKey(config.getPrimaryKey(), dbType, true, null));
313 | }
314 |
315 | if (config.isUseActualColumnNames()) {
316 | tableConfig.addProperty("useActualColumnNames", "true");
317 | }
318 |
319 | if (config.isUseTableNameAlias()) {
320 | tableConfig.setAlias(config.getTableName());
321 | }
322 |
323 | // if (ignoredColumns != null) {
324 | // ignoredColumns.stream().forEach(new Consumer() {
325 | // @Override
326 | // public void accept(IgnoredColumn ignoredColumn) {
327 | // tableConfig.addIgnoredColumn(ignoredColumn);
328 | // }
329 | // });
330 | // }
331 | // if (columnOverrides != null) {
332 | // for (ColumnOverride columnOverride : columnOverrides) {
333 | // tableConfig.addColumnOverride(columnOverride);
334 | // }
335 | // }
336 |
337 | tableConfig.setMapperName(config.getDaoName());
338 | return tableConfig;
339 | }
340 |
341 |
342 | /**
343 | * 生成实体类配置
344 | *
345 | * @return
346 | */
347 | private JavaModelGeneratorConfiguration buildModelConfig() {
348 | String projectFolder = config.getProjectFolder();
349 | String modelPackage = config.getModelPackage();
350 | String modelPackageTargetFolder = config.getModelTargetFolder();
351 | String modelMvnPath = config.getModelMvnPath();
352 |
353 | JavaModelGeneratorConfiguration modelConfig = new JavaModelGeneratorConfiguration();
354 |
355 | if (!StringUtils.isEmpty(modelPackage)) {
356 | modelConfig.setTargetPackage(modelPackage);
357 | } else {
358 | modelConfig.setTargetPackage("generator");
359 | }
360 |
361 | if (!StringUtils.isEmpty(modelPackageTargetFolder)) {
362 | modelConfig.setTargetProject(modelPackageTargetFolder + "/" + modelMvnPath + "/");
363 | } else {
364 | modelConfig.setTargetProject(projectFolder + "/" + modelMvnPath + "/");
365 | }
366 | return modelConfig;
367 | }
368 |
369 | /**
370 | * 生成mapper.xml文件配置
371 | *
372 | * @return
373 | */
374 | private SqlMapGeneratorConfiguration buildMapperXmlConfig() {
375 |
376 | String projectFolder = config.getProjectFolder();
377 | String mappingXMLPackage = config.getXmlPackage();
378 | String mappingXMLTargetFolder = config.getXmlTargetFolder();
379 | String xmlMvnPath = config.getXmlMvnPath();
380 |
381 | SqlMapGeneratorConfiguration mapperConfig = new SqlMapGeneratorConfiguration();
382 |
383 | if (!StringUtils.isEmpty(mappingXMLPackage)) {
384 | mapperConfig.setTargetPackage(mappingXMLPackage);
385 | } else {
386 | mapperConfig.setTargetPackage("generator");
387 | }
388 |
389 | if (!StringUtils.isEmpty(mappingXMLTargetFolder)) {
390 | mapperConfig.setTargetProject(mappingXMLTargetFolder + "/" + xmlMvnPath + "/");
391 | } else {
392 | mapperConfig.setTargetProject(projectFolder + "/" + xmlMvnPath + "/");
393 | }
394 |
395 | if (config.isOverrideXML()) {//14
396 | String mappingXMLFilePath = getMappingXMLFilePath(config);
397 | File mappingXMLFile = new File(mappingXMLFilePath);
398 | if (mappingXMLFile.exists()) {
399 | mappingXMLFile.delete();
400 | }
401 | }
402 |
403 | return mapperConfig;
404 | }
405 |
406 | /**
407 | * 生成dao接口文件配置
408 | *
409 | * @return
410 | */
411 | private JavaClientGeneratorConfiguration buildDaoConfig() {
412 |
413 | String projectFolder = config.getProjectFolder();
414 | String daoPackage = config.getDaoPackage();
415 | String daoTargetFolder = config.getDaoTargetFolder();
416 | String daoMvnPath = config.getDaoMvnPath();
417 |
418 | JavaClientGeneratorConfiguration daoConfig = new JavaClientGeneratorConfiguration();
419 | daoConfig.setConfigurationType("XMLMAPPER");
420 | daoConfig.setTargetPackage(daoPackage);
421 |
422 | if (!StringUtils.isEmpty(daoPackage)) {
423 | daoConfig.setTargetPackage(daoPackage);
424 | } else {
425 | daoConfig.setTargetPackage("generator");
426 | }
427 |
428 | if (!StringUtils.isEmpty(daoTargetFolder)) {
429 | daoConfig.setTargetProject(daoTargetFolder + "/" + daoMvnPath + "/");
430 | } else {
431 | daoConfig.setTargetProject(projectFolder + "/" + daoMvnPath + "/");
432 | }
433 |
434 | return daoConfig;
435 | }
436 |
437 | /**
438 | * 生成注释配置
439 | *
440 | * @return
441 | */
442 | private CommentGeneratorConfiguration buildCommentConfig() {
443 | CommentGeneratorConfiguration commentConfig = new CommentGeneratorConfiguration();
444 | commentConfig.setConfigurationType(DbRemarksCommentGenerator.class.getName());
445 |
446 | if (config.isComment()) {
447 | commentConfig.addProperty("columnRemarks", "true");
448 | }
449 | if (config.isAnnotation()) {
450 | commentConfig.addProperty("annotations", "true");
451 | }
452 |
453 | return commentConfig;
454 | }
455 |
456 | /**
457 | * 添加相关插件(注意插件文件需要通过jar引入)
458 | *
459 | * @param context
460 | */
461 | private void addPluginConfiguration(PsiElement psiElement, Context context) {
462 |
463 |
464 | //实体添加序列化
465 | PluginConfiguration serializablePlugin = new PluginConfiguration();
466 | serializablePlugin.addProperty("type", "org.mybatis.generator.plugins.SerializablePlugin");
467 | serializablePlugin.setConfigurationType("org.mybatis.generator.plugins.SerializablePlugin");
468 | context.addPluginConfiguration(serializablePlugin);
469 |
470 |
471 | if (config.isNeedToStringHashcodeEquals()) {
472 | PluginConfiguration equalsHashCodePlugin = new PluginConfiguration();
473 | equalsHashCodePlugin.addProperty("type", "org.mybatis.generator.plugins.EqualsHashCodePlugin");
474 | equalsHashCodePlugin.setConfigurationType("org.mybatis.generator.plugins.EqualsHashCodePlugin");
475 | context.addPluginConfiguration(equalsHashCodePlugin);
476 | PluginConfiguration toStringPluginPlugin = new PluginConfiguration();
477 | toStringPluginPlugin.addProperty("type", "org.mybatis.generator.plugins.ToStringPlugin");
478 | toStringPluginPlugin.setConfigurationType("org.mybatis.generator.plugins.ToStringPlugin");
479 | context.addPluginConfiguration(toStringPluginPlugin);
480 | }
481 |
482 | // limit/offset插件
483 | if (config.isOffsetLimit()) {
484 | if (DbType.MySQL.name().equals(DatabaseType)
485 | || DbType.PostgreSQL.name().equals(DatabaseType)) {
486 | PluginConfiguration mySQLLimitPlugin = new PluginConfiguration();
487 | mySQLLimitPlugin.addProperty("type", "cn.kt.MySQLLimitPlugin");
488 | mySQLLimitPlugin.setConfigurationType("cn.kt.MySQLLimitPlugin");
489 | context.addPluginConfiguration(mySQLLimitPlugin);
490 | }
491 | }
492 |
493 | //for JSR310
494 | if (config.isJsr310Support()) {
495 | JavaTypeResolverConfiguration javaTypeResolverPlugin = new JavaTypeResolverConfiguration();
496 | javaTypeResolverPlugin.setConfigurationType("cn.kt.JavaTypeResolverJsr310Impl");
497 | context.setJavaTypeResolverConfiguration(javaTypeResolverPlugin);
498 | }
499 |
500 | //forUpdate 插件
501 | if (config.isNeedForUpdate()) {
502 | if (DbType.MySQL.name().equals(DatabaseType)
503 | || DbType.PostgreSQL.name().equals(DatabaseType)) {
504 | PluginConfiguration mySQLForUpdatePlugin = new PluginConfiguration();
505 | mySQLForUpdatePlugin.addProperty("type", "cn.kt.MySQLForUpdatePlugin");
506 | mySQLForUpdatePlugin.setConfigurationType("cn.kt.MySQLForUpdatePlugin");
507 | context.addPluginConfiguration(mySQLForUpdatePlugin);
508 | }
509 | }
510 |
511 | //repository 插件
512 | if (config.isAnnotationDAO()) {
513 | if (DbType.MySQL.name().equals(DatabaseType)
514 | || DbType.PostgreSQL.name().equals(DatabaseType)) {
515 | PluginConfiguration repositoryPlugin = new PluginConfiguration();
516 | repositoryPlugin.addProperty("type", "cn.kt.RepositoryPlugin");
517 | repositoryPlugin.setConfigurationType("cn.kt.RepositoryPlugin");
518 | context.addPluginConfiguration(repositoryPlugin);
519 | }
520 | }
521 |
522 | if (config.isUseDAOExtendStyle()) {//13
523 | if (DbType.MySQL.name().equals(DatabaseType)
524 | || DbType.PostgreSQL.name().equals(DatabaseType)) {
525 | PluginConfiguration commonDAOInterfacePlugin = new PluginConfiguration();
526 | commonDAOInterfacePlugin.addProperty("type", "cn.kt.CommonDAOInterfacePlugin");
527 | commonDAOInterfacePlugin.setConfigurationType("cn.kt.CommonDAOInterfacePlugin");
528 | context.addPluginConfiguration(commonDAOInterfacePlugin);
529 | }
530 | }
531 |
532 | }
533 |
534 | /**
535 | * 获取xml文件路径 用以删除之前的xml
536 | *
537 | * @param config
538 | * @return
539 | */
540 | private String getMappingXMLFilePath(Config config) {
541 | StringBuilder sb = new StringBuilder();
542 | String mappingXMLPackage = config.getXmlPackage();
543 | String mappingXMLTargetFolder = config.getXmlTargetFolder();
544 | String xmlMvnPath = config.getXmlMvnPath();
545 | sb.append(mappingXMLTargetFolder + "/" + xmlMvnPath + "/");
546 |
547 | if (!StringUtils.isEmpty(mappingXMLPackage)) {
548 | sb.append(mappingXMLPackage.replace(".", "/")).append("/");
549 | }
550 | if (!StringUtils.isEmpty(config.getDaoName())) {
551 | sb.append(config.getDaoName()).append(".xml");
552 | } else {
553 | sb.append(config.getModelName()).append("Dao.xml");
554 | }
555 |
556 | return sb.toString();
557 | }
558 | }
559 |
--------------------------------------------------------------------------------
/src/cn/kt/model/Config.java:
--------------------------------------------------------------------------------
1 | package cn.kt.model;
2 |
3 | /**
4 | * 界面配置
5 | */
6 | public class Config {
7 |
8 | /**
9 | * 配置名称
10 | */
11 | private String name;
12 |
13 | /**
14 | * 表名
15 | */
16 | private String tableName;
17 |
18 | /**
19 | * 主键
20 | */
21 | private String primaryKey;
22 |
23 | /**
24 | * 实体名
25 | */
26 | private String modelName;
27 |
28 | /**
29 | * dao名称
30 | */
31 | private String daoName;
32 |
33 | /**
34 | * dao后缀
35 | */
36 | private String daoPostfix;
37 |
38 | /**
39 | * 工程目录
40 | */
41 | private String projectFolder;
42 |
43 | private String modelPackage;
44 | private String modelTargetFolder;
45 | private String modelMvnPath;
46 |
47 | private String daoPackage;
48 | private String daoTargetFolder;
49 | private String daoMvnPath;
50 |
51 | private String xmlPackage;
52 | private String xmlTargetFolder;
53 | private String xmlMvnPath;
54 |
55 | /**
56 | * 是否分页
57 | */
58 | private boolean offsetLimit;
59 |
60 | /**
61 | * 是否生成实体注释(来自表)
62 | */
63 | private boolean comment;
64 |
65 | /**
66 | * 是否覆盖原xml
67 | */
68 | private boolean overrideXML;
69 |
70 | /**
71 | * 是否生成toString/hashCode/equals方法
72 | */
73 | private boolean needToStringHashcodeEquals;
74 |
75 | /**
76 | * 是否使用Schema前缀
77 | */
78 | private boolean useSchemaPrefix;
79 |
80 | /**
81 | * 是否select 增加ForUpdate
82 | */
83 | private boolean needForUpdate;
84 |
85 | /**
86 | * 是否DAO使用 @Repository 注解
87 | */
88 | private boolean annotationDAO;
89 |
90 | /**
91 | * 是否DAO方法抽出到公共父接口
92 | */
93 | private boolean useDAOExtendStyle;
94 |
95 | /**
96 | * 是否JSR310: Date and Time API
97 | */
98 | private boolean jsr310Support;
99 |
100 | /**
101 | * 是否生成JPA注解
102 | */
103 | private boolean annotation;
104 |
105 | /**
106 | * 是否使用实际的列名
107 | */
108 | private boolean useActualColumnNames;
109 |
110 | /**
111 | * 是否启用as别名查询
112 | */
113 | private boolean useTableNameAlias;
114 |
115 | /**
116 | * 是否使用Example
117 | */
118 | private boolean useExample;
119 | /**
120 | * 是否是mysql8数据库
121 | */
122 | private boolean mysql_8;
123 |
124 | private String encoding;
125 | private String connectorJarPath;
126 |
127 | public boolean isJsr310Support() {
128 | return jsr310Support;
129 | }
130 |
131 | public void setJsr310Support(boolean jsr310Support) {
132 | this.jsr310Support = jsr310Support;
133 | }
134 |
135 | public boolean isUseSchemaPrefix() {
136 | return useSchemaPrefix;
137 | }
138 |
139 | public void setUseSchemaPrefix(boolean useSchemaPrefix) {
140 | this.useSchemaPrefix = useSchemaPrefix;
141 | }
142 |
143 | public boolean isUseExample() {
144 | return useExample;
145 | }
146 |
147 | public void setUseExample(boolean useExample) {
148 | this.useExample = useExample;
149 | }
150 |
151 | public String getName() {
152 | return name;
153 | }
154 |
155 | public void setName(String name) {
156 | this.name = name;
157 | }
158 |
159 | public String getTableName() {
160 | return tableName;
161 | }
162 |
163 | public void setTableName(String tableName) {
164 | this.tableName = tableName;
165 | }
166 |
167 | public String getModelName() {
168 | return modelName;
169 | }
170 |
171 | public void setModelName(String modelName) {
172 | this.modelName = modelName;
173 | }
174 |
175 | public String getConnectorJarPath() {
176 | return connectorJarPath;
177 | }
178 |
179 | public void setConnectorJarPath(String connectorJarPath) {
180 | this.connectorJarPath = connectorJarPath;
181 | }
182 |
183 | public String getProjectFolder() {
184 | return projectFolder;
185 | }
186 |
187 | public void setProjectFolder(String projectFolder) {
188 | this.projectFolder = projectFolder;
189 | }
190 |
191 | public String getModelPackage() {
192 | return modelPackage;
193 | }
194 |
195 | public void setModelPackage(String modelPackage) {
196 | this.modelPackage = modelPackage;
197 | }
198 |
199 | public String getModelTargetFolder() {
200 | return modelTargetFolder;
201 | }
202 |
203 | public void setModelTargetFolder(String modelTargetFolder) {
204 | this.modelTargetFolder = modelTargetFolder;
205 | }
206 |
207 | public String getDaoPackage() {
208 | return daoPackage;
209 | }
210 |
211 | public void setDaoPackage(String daoPackage) {
212 | this.daoPackage = daoPackage;
213 | }
214 |
215 | public String getDaoTargetFolder() {
216 | return daoTargetFolder;
217 | }
218 |
219 | public void setDaoTargetFolder(String daoTargetFolder) {
220 | this.daoTargetFolder = daoTargetFolder;
221 | }
222 |
223 | public String getXmlPackage() {
224 | return xmlPackage;
225 | }
226 |
227 | public void setXmlPackage(String xmlPackage) {
228 | this.xmlPackage = xmlPackage;
229 | }
230 |
231 | public String getXmlTargetFolder() {
232 | return xmlTargetFolder;
233 | }
234 |
235 | public void setXmlTargetFolder(String xmlTargetFolder) {
236 | this.xmlTargetFolder = xmlTargetFolder;
237 | }
238 |
239 | public boolean isOffsetLimit() {
240 | return offsetLimit;
241 | }
242 |
243 | public void setOffsetLimit(boolean offsetLimit) {
244 | this.offsetLimit = offsetLimit;
245 | }
246 |
247 | public boolean isComment() {
248 | return comment;
249 | }
250 |
251 | public void setComment(boolean comment) {
252 | this.comment = comment;
253 | }
254 |
255 | public boolean isNeedToStringHashcodeEquals() {
256 | return needToStringHashcodeEquals;
257 | }
258 |
259 | public void setNeedToStringHashcodeEquals(boolean needToStringHashcodeEquals) {
260 | this.needToStringHashcodeEquals = needToStringHashcodeEquals;
261 | }
262 |
263 | public boolean isNeedForUpdate() {
264 | return needForUpdate;
265 | }
266 |
267 | public void setNeedForUpdate(boolean needForUpdate) {
268 | this.needForUpdate = needForUpdate;
269 | }
270 |
271 | public boolean isAnnotationDAO() {
272 | return annotationDAO;
273 | }
274 |
275 | public void setAnnotationDAO(boolean annotationDAO) {
276 | this.annotationDAO = annotationDAO;
277 | }
278 |
279 | public boolean isAnnotation() {
280 | return annotation;
281 | }
282 |
283 | public void setAnnotation(boolean annotation) {
284 | this.annotation = annotation;
285 | }
286 |
287 | public boolean isUseActualColumnNames() {
288 | return useActualColumnNames;
289 | }
290 |
291 | public void setUseActualColumnNames(boolean useActualColumnNames) {
292 | this.useActualColumnNames = useActualColumnNames;
293 | }
294 |
295 | public String getDaoName() {
296 | return daoName;
297 | }
298 |
299 | public void setDaoName(String daoName) {
300 | this.daoName = daoName;
301 | }
302 |
303 | public String getPrimaryKey() {
304 | return primaryKey;
305 | }
306 |
307 | public void setPrimaryKey(String primaryKey) {
308 | this.primaryKey = primaryKey;
309 | }
310 |
311 | public String getEncoding() {
312 | return encoding;
313 | }
314 |
315 | public void setEncoding(String encoding) {
316 | this.encoding = encoding;
317 | }
318 |
319 | public boolean getUseTableNameAlias() {
320 | return useTableNameAlias;
321 | }
322 |
323 | public void setUseTableNameAlias(boolean useTableNameAlias) {
324 | this.useTableNameAlias = useTableNameAlias;
325 | }
326 |
327 | public boolean isUseTableNameAlias() {
328 | return useTableNameAlias;
329 | }
330 |
331 | public boolean isOverrideXML() {
332 | return overrideXML;
333 | }
334 |
335 | public void setOverrideXML(boolean overrideXML) {
336 | this.overrideXML = overrideXML;
337 | }
338 |
339 | public void setUseDAOExtendStyle(boolean useDAOExtendStyle) {
340 | this.useDAOExtendStyle = useDAOExtendStyle;
341 | }
342 |
343 | public boolean isUseDAOExtendStyle() {
344 | return useDAOExtendStyle;
345 | }
346 |
347 | public String getModelMvnPath() {
348 | return modelMvnPath;
349 | }
350 |
351 | public void setModelMvnPath(String modelMvnPath) {
352 | this.modelMvnPath = modelMvnPath;
353 | }
354 |
355 | public String getDaoMvnPath() {
356 | return daoMvnPath;
357 | }
358 |
359 | public void setDaoMvnPath(String daoMvnPath) {
360 | this.daoMvnPath = daoMvnPath;
361 | }
362 |
363 | public String getXmlMvnPath() {
364 | return xmlMvnPath;
365 | }
366 |
367 | public void setXmlMvnPath(String xmlMvnPath) {
368 | this.xmlMvnPath = xmlMvnPath;
369 | }
370 |
371 | public String getDaoPostfix() {
372 | return daoPostfix;
373 | }
374 |
375 | public void setDaoPostfix(String daoPostfix) {
376 | this.daoPostfix = daoPostfix;
377 | }
378 |
379 | public boolean isMysql_8() {
380 | return mysql_8;
381 | }
382 |
383 | public void setMysql_8(boolean mysql_8) {
384 | this.mysql_8 = mysql_8;
385 | }
386 | }
387 |
--------------------------------------------------------------------------------
/src/cn/kt/model/DbType.java:
--------------------------------------------------------------------------------
1 | package cn.kt.model;
2 |
3 | public enum DbType {
4 |
5 | MySQL("com.mysql.jdbc.Driver", "jdbc:mysql://%s:%s/%s?useUnicode=true&useSSL=false&characterEncoding=%s", "mysql-connector-java-5.1.38.jar"),
6 | MySQL_8("com.mysql.cj.jdbc.Driver", "jdbc:mysql://%s:%s/%s?serverTimezone=UTC&useUnicode=true&useSSL=false&characterEncoding=%s", "mysql-connector-java-8.0.11.jar"),
7 | Oracle("oracle.jdbc.driver.OracleDriver", "jdbc:oracle:thin:@%s:%s:%s", "ojdbc14.jar"),
8 | PostgreSQL("org.postgresql.Driver", "jdbc:postgresql://%s:%s/%s", "postgresql-9.4.1209.jar"),
9 | SqlServer("com.microsoft.sqlserver.jdbc.SQLServerDriver", "jdbc:sqlserver://%s:%s;databaseName=%s", "sqljdbc4-4.0.jar"),
10 | Sqlite("org.sqlite.JDBC", "jdbc:sqlite:%s", "sqlite-jdbc-3.19.3.jar"),
11 | MariaDB("org.mariadb.jdbc.Driver", "", "mariadb-java-client-2.3.0.jar");
12 |
13 | private final String driverClass;
14 | private final String connectionUrlPattern;
15 | private final String connectorJarFile;
16 |
17 | DbType(String driverClass, String connectionUrlPattern, String connectorJarFile) {
18 | this.driverClass = driverClass;
19 | this.connectionUrlPattern = connectionUrlPattern;
20 | this.connectorJarFile = connectorJarFile;
21 | }
22 |
23 | public String getDriverClass() {
24 | return driverClass;
25 | }
26 |
27 | public String getConnectionUrlPattern() {
28 | return connectionUrlPattern;
29 | }
30 |
31 | public String getConnectorJarFile() {
32 | return connectorJarFile;
33 | }
34 | }
--------------------------------------------------------------------------------
/src/cn/kt/model/TableInfo.java:
--------------------------------------------------------------------------------
1 | package cn.kt.model;
2 |
3 | import com.intellij.database.model.DasColumn;
4 | import com.intellij.database.psi.DbTable;
5 | import com.intellij.database.util.DasUtil;
6 | import com.intellij.util.containers.JBIterable;
7 |
8 | import java.util.ArrayList;
9 | import java.util.HashSet;
10 | import java.util.List;
11 | import java.util.Set;
12 |
13 | public class TableInfo {
14 |
15 | public final DbTable tableElement;
16 |
17 | private List columns = new ArrayList();
18 |
19 | private List primaryKeys = new ArrayList();
20 |
21 |
22 | public TableInfo(DbTable tableElement) {
23 | this.tableElement = tableElement;
24 | List columns = new ArrayList();
25 |
26 | JBIterable extends DasColumn> columnsIter = DasUtil.getColumns(tableElement);
27 | List extends DasColumn> dasColumns = columnsIter.toList();
28 | for (DasColumn dasColumn : dasColumns) {
29 | columns.add(dasColumn);
30 |
31 | if (DasUtil.isPrimary(dasColumn)) {
32 | primaryKeys.add(dasColumn.getName());
33 | }
34 |
35 | }
36 |
37 | this.columns = columns;
38 | }
39 |
40 | public String getTableName() {
41 | return tableElement.getName();
42 | }
43 |
44 | public List getColumns() {
45 | return columns;
46 | }
47 |
48 | public List getColumnsName() {
49 | List columnsName = new ArrayList();
50 | for (DasColumn column : columns) {
51 | columnsName.add(column.getName());
52 | }
53 | return columnsName;
54 | }
55 |
56 | public List getPrimaryKeys() {
57 | return this.primaryKeys;
58 | }
59 |
60 | public List getNonPrimaryColumns() {
61 | Set pKNameSet = new HashSet();
62 | for (String pkName : getPrimaryKeys()) {
63 | pKNameSet.add(pkName);
64 | }
65 |
66 | List ret = new ArrayList();
67 | for (DasColumn column : columns) {
68 | if (!pKNameSet.contains(column.getName())) {
69 | ret.add(column);
70 | }
71 | }
72 |
73 | return ret;
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/cn/kt/model/User.java:
--------------------------------------------------------------------------------
1 | package cn.kt.model;
2 |
3 | /**
4 | * 保存数据库连接对应的用户名,密码存在keepass库中
5 | * Created by kangtian on 2018/8/3.
6 | */
7 | public class User {
8 |
9 | //用户名
10 | private String username;
11 |
12 |
13 | public User() {
14 | }
15 |
16 | public User(String username) {
17 | this.username = username;
18 |
19 | }
20 |
21 |
22 |
23 | public String getUsername() {
24 | return username;
25 | }
26 |
27 | public void setUsername(String username) {
28 | this.username = username;
29 | }
30 |
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/cn/kt/setting/PersistentConfig.java:
--------------------------------------------------------------------------------
1 | package cn.kt.setting;
2 |
3 | import cn.kt.model.Config;
4 | import cn.kt.model.User;
5 | import com.intellij.openapi.components.PersistentStateComponent;
6 | import com.intellij.openapi.components.ServiceManager;
7 | import com.intellij.openapi.components.State;
8 | import com.intellij.openapi.components.Storage;
9 | import com.intellij.openapi.project.Project;
10 | import com.intellij.util.xmlb.XmlSerializerUtil;
11 | import org.jetbrains.annotations.Nullable;
12 |
13 | import java.util.Map;
14 |
15 |
16 | /**
17 | * 配置持久化
18 | */
19 | @State(name = "PersistentConfig", storages = {@Storage("generator-config.xml")})
20 | public class PersistentConfig implements PersistentStateComponent {
21 |
22 | private Map initConfig;
23 | private Map users;
24 | private Map historyConfigList;
25 |
26 | @Nullable
27 | public static PersistentConfig getInstance(Project project) {
28 | return ServiceManager.getService(project, PersistentConfig.class);
29 | }
30 |
31 | @Nullable
32 | public PersistentConfig getState() {
33 | return this;
34 | }
35 |
36 | @Override
37 | public void loadState(PersistentConfig persistentConfig) {
38 | XmlSerializerUtil.copyBean(persistentConfig, this);
39 | }
40 |
41 |
42 | public Map getInitConfig() {
43 | return initConfig;
44 | }
45 |
46 | public void setInitConfig(Map initConfig) {
47 | this.initConfig = initConfig;
48 | }
49 |
50 | public Map getUsers() {
51 | return users;
52 | }
53 |
54 | public void setUsers(Map users) {
55 | this.users = users;
56 | }
57 |
58 | public Map getHistoryConfigList() {
59 | return historyConfigList;
60 | }
61 |
62 | public void setHistoryConfigList(Map historyConfigList) {
63 | this.historyConfigList = historyConfigList;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/src/cn/kt/setting/SettingConfigurable.java:
--------------------------------------------------------------------------------
1 | package cn.kt.setting;
2 |
3 | import cn.kt.ui.SettingUI;
4 | import com.intellij.openapi.options.ConfigurationException;
5 | import com.intellij.openapi.options.SearchableConfigurable;
6 | import com.intellij.openapi.project.Project;
7 | import com.sun.istack.internal.NotNull;
8 | import org.jetbrains.annotations.Nls;
9 | import org.jetbrains.annotations.Nullable;
10 |
11 | import javax.swing.*;
12 |
13 | /**
14 | *配置设置界面
15 | * Created by kangtian on 2018/7/18.
16 | */
17 | public class SettingConfigurable implements SearchableConfigurable {
18 | private SettingUI mainPanel;
19 |
20 | @SuppressWarnings("FieldCanBeLocal")
21 | private final Project project;
22 |
23 |
24 | public SettingConfigurable(@NotNull Project project) {
25 | this.project = project;
26 | }
27 |
28 | @Nls
29 | @Override
30 | public String getDisplayName() {
31 | return "Mybatis gene plugin";
32 | }
33 |
34 | @Nullable
35 | @Override
36 | public String getHelpTopic() {
37 | return "gene.helpTopic";
38 | }
39 |
40 | @NotNull
41 | @Override
42 | public String getId() {
43 | return "gene.id";
44 | }
45 |
46 | @Nullable
47 | @Override
48 | public Runnable enableSearch(String s) {
49 | return null;
50 | }
51 |
52 | @Nullable
53 | @Override
54 | public JComponent createComponent() {
55 | mainPanel = new SettingUI();
56 | mainPanel.createUI(project);
57 | return mainPanel.getContentPane();
58 | }
59 |
60 | @Override
61 | public boolean isModified() {
62 | return mainPanel.isModified();
63 | }
64 |
65 | @Override
66 | public void apply() throws ConfigurationException {
67 | mainPanel.apply();
68 | }
69 |
70 | @Override
71 | public void reset() {
72 | mainPanel.reset();
73 | }
74 |
75 | @Override
76 | public void disposeUIResources() {
77 | mainPanel = null;
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/cn/kt/ui/MainUI.java:
--------------------------------------------------------------------------------
1 | package cn.kt.ui;
2 |
3 | import cn.kt.generate.Generate;
4 | import cn.kt.model.Config;
5 | import cn.kt.model.TableInfo;
6 | import cn.kt.setting.PersistentConfig;
7 | import cn.kt.util.JTextFieldHintListener;
8 | import cn.kt.util.StringUtils;
9 | import com.intellij.database.psi.DbTable;
10 | import com.intellij.ide.util.PackageChooserDialog;
11 | import com.intellij.openapi.actionSystem.AnActionEvent;
12 | import com.intellij.openapi.actionSystem.LangDataKeys;
13 | import com.intellij.openapi.actionSystem.PlatformDataKeys;
14 | import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
15 | import com.intellij.openapi.project.Project;
16 | import com.intellij.openapi.ui.TextBrowseFolderListener;
17 | import com.intellij.openapi.ui.TextFieldWithBrowseButton;
18 | import com.intellij.psi.PsiElement;
19 | import com.intellij.psi.PsiPackage;
20 | import com.intellij.ui.components.*;
21 |
22 | import javax.swing.*;
23 | import javax.swing.border.Border;
24 | import javax.swing.border.EmptyBorder;
25 | import java.awt.*;
26 | import java.awt.event.*;
27 | import java.util.HashMap;
28 | import java.util.Map;
29 |
30 | /**
31 | * 插件主界面
32 | * Created by kangtian on 2018/8/1.
33 | */
34 | public class MainUI extends JFrame {
35 |
36 |
37 | private AnActionEvent anActionEvent;
38 | private Project project;
39 | private PersistentConfig persistentConfig;
40 | private PsiElement[] psiElements;
41 | private Map initConfigMap;
42 | private Map historyConfigList;
43 | private Config config;
44 |
45 |
46 | private JPanel contentPane = new JBPanel<>();
47 | private JButton buttonOK = new JButton("ok");
48 | private JButton buttonCancel = new JButton("cancle");
49 | private JButton selectConfigBtn = new JButton("SELECT");
50 | private JButton deleteConfigBtn = new JButton("DELETE");
51 |
52 |
53 | private JTextField tableNameField = new JTextField(10);
54 | private JBTextField modelPackageField = new JBTextField(12);
55 | private JBTextField daoPackageField = new JBTextField(12);
56 | private JBTextField xmlPackageField = new JBTextField(12);
57 | private JTextField mapperNameField = new JTextField(10);
58 | private JTextField modelNameField = new JTextField(10);
59 | private JTextField keyField = new JTextField(10);
60 |
61 | private TextFieldWithBrowseButton projectFolderBtn = new TextFieldWithBrowseButton();
62 | private TextFieldWithBrowseButton modelFolderBtn = new TextFieldWithBrowseButton();
63 | private TextFieldWithBrowseButton daoFolderBtn = new TextFieldWithBrowseButton();
64 | private TextFieldWithBrowseButton xmlFolderBtn = new TextFieldWithBrowseButton();
65 | private JTextField modelMvnField = new JBTextField(15);
66 | private JTextField daoMvnField = new JBTextField(15);
67 | private JTextField xmlMvnField = new JBTextField(15);
68 | private JButton setProjectBtn = new JButton("Set-Project-Path");
69 |
70 | private JCheckBox offsetLimitBox = new JCheckBox("Page(分页)");
71 | private JCheckBox commentBox = new JCheckBox("comment(实体注释)");
72 | private JCheckBox overrideXMLBox = new JCheckBox("Overwrite-Xml");
73 | private JCheckBox needToStringHashcodeEqualsBox = new JCheckBox("toString/hashCode/equals");
74 | private JCheckBox useSchemaPrefixBox = new JCheckBox("Use-Schema(使用Schema前缀)");
75 | private JCheckBox needForUpdateBox = new JCheckBox("Add-ForUpdate(select增加ForUpdate)");
76 | private JCheckBox annotationDAOBox = new JCheckBox("Repository-Annotation(Repository注解)");
77 | private JCheckBox useDAOExtendStyleBox = new JCheckBox("Parent-Interface(公共父接口)");
78 | private JCheckBox jsr310SupportBox = new JCheckBox("JSR310: Date and Time API");
79 | private JCheckBox annotationBox = new JCheckBox("JPA-Annotation(JPA注解)");
80 | private JCheckBox useActualColumnNamesBox = new JCheckBox("Actual-Column(实际的列名)");
81 | private JCheckBox useTableNameAliasBox = new JCheckBox("Use-Alias(启用别名查询)");
82 | private JCheckBox useExampleBox = new JCheckBox("Use-Example");
83 | private JCheckBox mysql_8Box = new JCheckBox("mysql_8");
84 |
85 |
86 |
87 | public MainUI(AnActionEvent anActionEvent) throws HeadlessException {
88 | this.anActionEvent = anActionEvent;
89 | this.project = anActionEvent.getData(PlatformDataKeys.PROJECT);
90 | this.persistentConfig = PersistentConfig.getInstance(project);
91 | this.psiElements = anActionEvent.getData(LangDataKeys.PSI_ELEMENT_ARRAY);
92 |
93 | initConfigMap = persistentConfig.getInitConfig();
94 | historyConfigList = persistentConfig.getHistoryConfigList();
95 |
96 |
97 |
98 | setTitle("mybatis generate tool");
99 | setPreferredSize(new Dimension(1200, 700));//设置大小
100 | setLocation(120, 100);
101 | pack();
102 | setVisible(true);
103 | getRootPane().setDefaultButton(buttonOK);
104 | setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
105 |
106 | PsiElement psiElement = psiElements[0];
107 | TableInfo tableInfo = new TableInfo((DbTable) psiElement);
108 | String tableName = tableInfo.getTableName();
109 | String modelName = StringUtils.dbStringToCamelStyle(tableName);
110 | String primaryKey = "";
111 | if(tableInfo.getPrimaryKeys().size()>0){
112 | primaryKey = tableInfo.getPrimaryKeys().get(0);
113 | }
114 | String projectFolder = project.getBasePath();
115 |
116 |
117 | if (psiElements.length > 1) {//多表时,只使用默认配置
118 | if (initConfigMap != null) {
119 | config = initConfigMap.get("initConfig");
120 | }
121 | } else {
122 | if (initConfigMap != null) {//单表时,优先使用已经存在的配置
123 | config = initConfigMap.get("initConfig");
124 | ;
125 | }
126 | if (historyConfigList == null) {
127 | historyConfigList = new HashMap<>();
128 | } else {
129 | if (historyConfigList.containsKey(tableName)) {
130 | config = historyConfigList.get(tableName);
131 | }
132 | }
133 | }
134 |
135 |
136 | contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
137 | contentPane.setLayout(new BorderLayout());
138 |
139 | JPanel paneMain = new JPanel(new GridLayout(2, 1, 3, 3));//主要设置显示在这里
140 | JPanel paneMainTop = new JPanel(new FlowLayout(FlowLayout.LEFT));
141 | paneMainTop.setBorder(new EmptyBorder(10, 30, 5, 40));
142 |
143 | JPanel paneMainTop1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
144 | JPanel paneMainTop2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
145 | JPanel paneMainTop3 = new JPanel(new GridLayout(4, 1, 3, 3));
146 | paneMainTop.add(paneMainTop1);
147 | paneMainTop.add(paneMainTop2);
148 | paneMainTop.add(paneMainTop3);
149 |
150 |
151 | JPanel paneLeft1 = new JPanel();
152 | paneLeft1.setLayout(new FlowLayout(FlowLayout.CENTER));
153 | JLabel tablejLabel = new JLabel("table name:");
154 | tablejLabel.setSize(new Dimension(20, 30));
155 | paneLeft1.add(tablejLabel);
156 | if (psiElements.length > 1) {
157 | tableNameField.addFocusListener(new JTextFieldHintListener(tableNameField, "eg:db_table"));
158 | } else {
159 | tableNameField.setText(tableName);
160 | }
161 | paneLeft1.add(tableNameField);
162 |
163 | JPanel paneLeft2 = new JPanel();
164 | paneLeft2.setLayout(new FlowLayout(FlowLayout.CENTER));
165 | paneLeft2.add(new JLabel("主键(选填):"));
166 | if (psiElements.length > 1) {
167 | keyField.addFocusListener(new JTextFieldHintListener(keyField, "eg:primary key"));
168 | } else {
169 | keyField.setText(primaryKey);
170 | }
171 | paneLeft2.add(keyField);
172 |
173 | JPanel paneRight1 = new JPanel();
174 | paneRight1.setLayout(new FlowLayout(FlowLayout.CENTER));
175 | paneRight1.add(new JLabel("model :"));
176 | if (psiElements.length > 1) {
177 | modelNameField.addFocusListener(new JTextFieldHintListener(modelNameField, "eg:DbTable"));
178 | } else {
179 | modelNameField.setText(modelName);
180 | }
181 | paneRight1.add(modelNameField);
182 |
183 | JPanel paneRight2 = new JPanel();
184 | paneRight2.setLayout(new FlowLayout(FlowLayout.CENTER));
185 | paneRight2.add(new JLabel("dao name:"));
186 | if (psiElements.length > 1) {
187 | if (config != null && !StringUtils.isEmpty(config.getDaoPostfix())) {
188 | mapperNameField.addFocusListener(new JTextFieldHintListener(mapperNameField, "eg:DbTable" + config.getDaoPostfix()));
189 | } else {
190 | mapperNameField.addFocusListener(new JTextFieldHintListener(mapperNameField, "eg:DbTable" + "Dao"));
191 | }
192 | } else {
193 | if (config != null && !StringUtils.isEmpty(config.getDaoPostfix())) {
194 | mapperNameField.setText(modelName + config.getDaoPostfix());
195 | } else {
196 | mapperNameField.setText(modelName + "Dao");
197 | }
198 | }
199 | paneRight2.add(mapperNameField);
200 |
201 | paneMainTop1.add(paneLeft1);
202 | paneMainTop1.add(paneLeft2);
203 | paneMainTop1.add(paneRight1);
204 | paneMainTop1.add(paneRight2);
205 |
206 | JPanel modelPackagePanel = new JPanel();
207 | modelPackagePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
208 | JBLabel labelLeft4 = new JBLabel("model package:");
209 | modelPackagePanel.add(labelLeft4);
210 | if (config != null && !StringUtils.isEmpty(config.getModelPackage())) {
211 | modelPackageField.setText(config.getModelPackage());
212 | } else {
213 | modelPackageField.setText("generator");
214 | }
215 | modelPackagePanel.add(modelPackageField);
216 | JButton packageBtn1 = new JButton("...");
217 | packageBtn1.addActionListener(actionEvent -> {
218 | final PackageChooserDialog chooser = new PackageChooserDialog("chooser model package", project);
219 | chooser.selectPackage(modelPackageField.getText());
220 | chooser.show();
221 | final PsiPackage psiPackage = chooser.getSelectedPackage();
222 | String packageName = psiPackage == null ? null : psiPackage.getQualifiedName();
223 | modelPackageField.setText(packageName);
224 | MainUI.this.toFront();
225 | });
226 | modelPackagePanel.add(packageBtn1);
227 |
228 |
229 | JPanel daoPackagePanel = new JPanel();
230 | daoPackagePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
231 | JLabel labelLeft5 = new JLabel("dao package:");
232 | daoPackagePanel.add(labelLeft5);
233 |
234 |
235 | if (config != null && !StringUtils.isEmpty(config.getDaoPackage())) {
236 | daoPackageField.setText(config.getDaoPackage());
237 | } else {
238 | daoPackageField.setText("generator");
239 | }
240 | daoPackagePanel.add(daoPackageField);
241 |
242 | JButton packageBtn2 = new JButton("...");
243 | packageBtn2.addActionListener(actionEvent -> {
244 | final PackageChooserDialog chooser = new PackageChooserDialog("choose dao package", project);
245 | chooser.selectPackage(daoPackageField.getText());
246 | chooser.show();
247 | final PsiPackage psiPackage = chooser.getSelectedPackage();
248 | String packageName = psiPackage == null ? null : psiPackage.getQualifiedName();
249 | daoPackageField.setText(packageName);
250 | MainUI.this.toFront();
251 | });
252 | daoPackagePanel.add(packageBtn2);
253 |
254 | JPanel xmlPackagePanel = new JPanel();
255 | xmlPackagePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
256 | JLabel labelLeft6 = new JLabel("xml package:");
257 | xmlPackagePanel.add(labelLeft6);
258 | if (config != null && !StringUtils.isEmpty(config.getXmlPackage())) {
259 | xmlPackageField.setText(config.getXmlPackage());
260 | } else {
261 | xmlPackageField.setText("generator");
262 | }
263 | xmlPackagePanel.add(xmlPackageField);
264 |
265 | paneMainTop2.add(modelPackagePanel);
266 | paneMainTop2.add(daoPackagePanel);
267 | paneMainTop2.add(xmlPackagePanel);
268 |
269 |
270 | JPanel projectFolderPanel = new JPanel();
271 | projectFolderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
272 | JLabel projectLabel = new JLabel("project folder:");
273 | projectFolderPanel.add(projectLabel);
274 | projectFolderBtn.setTextFieldPreferredWidth(45);
275 | if (config != null && !StringUtils.isEmpty(config.getProjectFolder())) {
276 | projectFolderBtn.setText(config.getProjectFolder());
277 | } else {
278 | projectFolderBtn.setText(projectFolder);
279 | }
280 | projectFolderBtn.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) {
281 | @Override
282 | public void actionPerformed(ActionEvent e) {
283 | super.actionPerformed(e);
284 | projectFolderBtn.setText(projectFolderBtn.getText().replaceAll("\\\\", "/"));
285 | }
286 | });
287 | projectFolderPanel.add(projectFolderBtn);
288 | projectFolderPanel.add(setProjectBtn);
289 |
290 |
291 | JPanel modelFolderPanel = new JPanel();
292 | modelFolderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
293 | modelFolderPanel.add(new JLabel("model folder:"));
294 |
295 | modelFolderBtn.setTextFieldPreferredWidth(45);
296 | if (config != null && !StringUtils.isEmpty(config.getModelTargetFolder())) {
297 | modelFolderBtn.setText(config.getModelTargetFolder());
298 | } else {
299 | modelFolderBtn.setText(projectFolder);
300 | }
301 | modelFolderBtn.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) {
302 | @Override
303 | public void actionPerformed(ActionEvent e) {
304 | super.actionPerformed(e);
305 | modelFolderBtn.setText(modelFolderBtn.getText().replaceAll("\\\\", "/"));
306 | }
307 | });
308 | modelFolderPanel.add(modelFolderBtn);
309 | modelFolderPanel.add(new JLabel("mvn path:"));
310 | modelMvnField.setText("src/main/java");
311 | modelFolderPanel.add(modelMvnField);
312 |
313 |
314 | JPanel daoFolderPanel = new JPanel();
315 | daoFolderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
316 | daoFolderPanel.add(new JLabel("dao folder:"));
317 | daoFolderBtn.setTextFieldPreferredWidth(45);
318 | if (config != null && !StringUtils.isEmpty(config.getDaoTargetFolder())) {
319 | daoFolderBtn.setText(config.getDaoTargetFolder());
320 | } else {
321 | daoFolderBtn.setText(projectFolder);
322 | }
323 | daoFolderBtn.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) {
324 | @Override
325 | public void actionPerformed(ActionEvent e) {
326 | super.actionPerformed(e);
327 | daoFolderBtn.setText(daoFolderBtn.getText().replaceAll("\\\\", "/"));
328 | }
329 | });
330 | daoFolderPanel.add(daoFolderBtn);
331 | daoFolderPanel.add(new JLabel("mvn path:"));
332 | daoMvnField.setText("src/main/java");
333 | daoFolderPanel.add(daoMvnField);
334 |
335 |
336 | JPanel xmlFolderPanel = new JPanel();
337 | xmlFolderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
338 | xmlFolderPanel.add(new JLabel("xml folder:"));
339 |
340 | xmlFolderBtn.setTextFieldPreferredWidth(45);
341 | if (config != null && !StringUtils.isEmpty(config.getXmlTargetFolder())) {
342 | xmlFolderBtn.setText(config.getXmlTargetFolder());
343 | } else {
344 | xmlFolderBtn.setText(projectFolder);
345 | }
346 | xmlFolderBtn.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) {
347 | });
348 | xmlFolderPanel.add(xmlFolderBtn);
349 | xmlFolderPanel.add(new JLabel("mvn path:"));
350 | xmlMvnField.setText("src/main/resources");
351 | xmlFolderPanel.add(xmlMvnField);
352 |
353 | paneMainTop3.add(projectFolderPanel);
354 | paneMainTop3.add(modelFolderPanel);
355 | paneMainTop3.add(daoFolderPanel);
356 | paneMainTop3.add(xmlFolderPanel);
357 |
358 | if (config == null) {
359 | offsetLimitBox.setSelected(true);
360 | commentBox.setSelected(true);
361 | overrideXMLBox.setSelected(true);
362 | needToStringHashcodeEqualsBox.setSelected(true);
363 | useSchemaPrefixBox.setSelected(true);
364 | useExampleBox.setSelected(true);
365 |
366 | } else {
367 | if (config.isOffsetLimit()) {
368 | offsetLimitBox.setSelected(true);
369 | }
370 | if (config.isComment()) {
371 | commentBox.setSelected(true);
372 | }
373 |
374 | if (config.isOverrideXML()) {
375 | overrideXMLBox.setSelected(true);
376 | }
377 | if (config.isNeedToStringHashcodeEquals()) {
378 | needToStringHashcodeEqualsBox.setSelected(true);
379 | }
380 | if (config.isUseSchemaPrefix()) {
381 | useSchemaPrefixBox.setSelected(true);
382 | }
383 | if (config.isNeedForUpdate()) {
384 | needForUpdateBox.setSelected(true);
385 | }
386 | if (config.isAnnotationDAO()) {
387 | annotationDAOBox.setSelected(true);
388 | }
389 | if (config.isUseDAOExtendStyle()) {
390 | useDAOExtendStyleBox.setSelected(true);
391 | }
392 | if (config.isJsr310Support()) {
393 | jsr310SupportBox.setSelected(true);
394 | }
395 | if (config.isAnnotation()) {
396 | annotationBox.setSelected(true);
397 | }
398 | if (config.isUseActualColumnNames()) {
399 | useActualColumnNamesBox.setSelected(true);
400 | }
401 | if (config.isUseTableNameAlias()) {
402 | useTableNameAliasBox.setSelected(true);
403 | }
404 | if (config.isUseExample()) {
405 | useExampleBox.setSelected(true);
406 | }
407 | if (config.isMysql_8()) {
408 | mysql_8Box.setSelected(true);
409 | }
410 | }
411 |
412 |
413 | JBPanel paneMainDown = new JBPanel(new GridLayout(5, 5, 5, 5));
414 | paneMainDown.setBorder(new EmptyBorder(2, 80, 100, 40));
415 |
416 | paneMainDown.add(offsetLimitBox);
417 | paneMainDown.add(commentBox);
418 | paneMainDown.add(overrideXMLBox);
419 | paneMainDown.add(needToStringHashcodeEqualsBox);
420 | paneMainDown.add(useSchemaPrefixBox);
421 | paneMainDown.add(needForUpdateBox);
422 | paneMainDown.add(annotationDAOBox);
423 | paneMainDown.add(useDAOExtendStyleBox);
424 | paneMainDown.add(jsr310SupportBox);
425 | paneMainDown.add(annotationBox);
426 | paneMainDown.add(useActualColumnNamesBox);
427 | paneMainDown.add(useTableNameAliasBox);
428 | paneMainDown.add(useExampleBox);
429 | paneMainDown.add(mysql_8Box);
430 |
431 | paneMain.add(paneMainTop);
432 | paneMain.add(paneMainDown);
433 |
434 |
435 | JPanel paneBottom = new JPanel();//确认和取消按钮
436 | paneBottom.setLayout(new FlowLayout(2));
437 | paneBottom.add(buttonOK);
438 | paneBottom.add(buttonCancel);
439 |
440 |
441 | JPanel panelLeft = new JPanel();
442 | panelLeft.setLayout(new BoxLayout(panelLeft, BoxLayout.Y_AXIS));
443 | this.getContentPane().add(Box.createVerticalStrut(10)); //采用x布局时,添加固定宽度组件隔开
444 | final DefaultListModel defaultListModel = new DefaultListModel();
445 |
446 | Border historyBorder = BorderFactory.createTitledBorder("history config:");
447 | panelLeft.setBorder(historyBorder);
448 |
449 |
450 | if (historyConfigList == null) {
451 | historyConfigList = new HashMap<>();
452 | }
453 | for (String historyConfigName : historyConfigList.keySet()) {
454 | defaultListModel.addElement(historyConfigName);
455 | }
456 | Map finalHistoryConfigList = historyConfigList;
457 |
458 | final JBList fruitList = new JBList(defaultListModel);
459 | fruitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
460 | fruitList.setSelectedIndex(0);
461 | fruitList.setVisibleRowCount(25);
462 | JBScrollPane ScrollPane = new JBScrollPane(fruitList);
463 | panelLeft.add(ScrollPane);
464 |
465 | JPanel btnPanel = new JPanel();
466 | btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS));
467 |
468 | btnPanel.add(selectConfigBtn);
469 | btnPanel.add(deleteConfigBtn);
470 | selectConfigBtn.addActionListener(new ActionListener() {
471 | @Override
472 | public void actionPerformed(ActionEvent e) {
473 | String configName = (String) fruitList.getSelectedValue();
474 | Config selectedConfig = finalHistoryConfigList.get(configName);
475 | modelPackageField.setText(selectedConfig.getModelPackage());
476 | daoPackageField.setText(selectedConfig.getDaoPackage());
477 | xmlPackageField.setText(selectedConfig.getXmlPackage());
478 | projectFolderBtn.setText(selectedConfig.getProjectFolder());
479 | modelFolderBtn.setText(selectedConfig.getModelTargetFolder());
480 | daoFolderBtn.setText(selectedConfig.getDaoTargetFolder());
481 | xmlFolderBtn.setText(selectedConfig.getXmlTargetFolder());
482 |
483 | offsetLimitBox.setSelected(selectedConfig.isOffsetLimit());
484 | commentBox.setSelected(selectedConfig.isComment());
485 | overrideXMLBox.setSelected(selectedConfig.isOverrideXML());
486 | needToStringHashcodeEqualsBox.setSelected(selectedConfig.isNeedToStringHashcodeEquals());
487 | useSchemaPrefixBox.setSelected(selectedConfig.isUseSchemaPrefix());
488 | needForUpdateBox.setSelected(selectedConfig.isNeedForUpdate());
489 | annotationDAOBox.setSelected(selectedConfig.isAnnotationDAO());
490 | useDAOExtendStyleBox.setSelected(selectedConfig.isUseDAOExtendStyle());
491 | jsr310SupportBox.setSelected(selectedConfig.isJsr310Support());
492 | annotationBox.setSelected(selectedConfig.isAnnotation());
493 | useActualColumnNamesBox.setSelected(selectedConfig.isUseActualColumnNames());
494 | useTableNameAliasBox.setSelected(selectedConfig.isUseTableNameAlias());
495 | useExampleBox.setSelected(selectedConfig.isUseExample());
496 | mysql_8Box.setSelected(selectedConfig.isMysql_8());
497 |
498 | }
499 | });
500 | deleteConfigBtn.addActionListener(new ActionListener() {
501 | @Override
502 | public void actionPerformed(ActionEvent e) {
503 | finalHistoryConfigList.remove(fruitList.getSelectedValue());
504 | defaultListModel.removeAllElements();
505 | for (String historyConfigName : finalHistoryConfigList.keySet()) {
506 | defaultListModel.addElement(historyConfigName);
507 | }
508 | }
509 | });
510 | panelLeft.add(btnPanel);
511 |
512 |
513 | contentPane.add(paneMain, BorderLayout.CENTER);
514 | contentPane.add(paneBottom, BorderLayout.SOUTH);
515 | contentPane.add(panelLeft, BorderLayout.WEST);
516 |
517 | setContentPane(contentPane);
518 |
519 | setProjectBtn.addActionListener(new ActionListener() {
520 | @Override
521 | public void actionPerformed(ActionEvent e) {
522 | modelFolderBtn.setText(projectFolderBtn.getText());
523 | daoFolderBtn.setText(projectFolderBtn.getText());
524 | xmlFolderBtn.setText(projectFolderBtn.getText());
525 | }
526 | });
527 |
528 | buttonOK.addActionListener(new ActionListener() {
529 | public void actionPerformed(ActionEvent e) {
530 | onOK();
531 | }
532 | });
533 |
534 |
535 | buttonCancel.addActionListener(new ActionListener() {
536 | public void actionPerformed(ActionEvent e) {
537 | onCancel();
538 | }
539 | });
540 |
541 | addWindowListener(new WindowAdapter() {
542 | public void windowClosing(WindowEvent e) {
543 | onCancel();
544 | }
545 | });
546 |
547 | contentPane.registerKeyboardAction(new ActionListener() {
548 | public void actionPerformed(ActionEvent e) {
549 | onCancel();
550 | }
551 | }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
552 | }
553 |
554 | private void onOK() {
555 | try {
556 | dispose();
557 |
558 | if (psiElements.length == 1) {
559 | Config generator_config = new Config();
560 | generator_config.setName(tableNameField.getText());
561 | generator_config.setTableName(tableNameField.getText());
562 | generator_config.setProjectFolder(projectFolderBtn.getText());
563 |
564 | generator_config.setModelPackage(modelPackageField.getText());
565 | generator_config.setModelTargetFolder(modelFolderBtn.getText());
566 | generator_config.setDaoPackage(daoPackageField.getText());
567 | generator_config.setDaoTargetFolder(daoFolderBtn.getText());
568 | generator_config.setXmlPackage(xmlPackageField.getText());
569 | generator_config.setXmlTargetFolder(xmlFolderBtn.getText());
570 | generator_config.setDaoName(mapperNameField.getText());
571 | generator_config.setModelName(modelNameField.getText());
572 | generator_config.setPrimaryKey(keyField.getText());
573 |
574 | generator_config.setOffsetLimit(offsetLimitBox.getSelectedObjects() != null);
575 | generator_config.setComment(commentBox.getSelectedObjects() != null);
576 | generator_config.setOverrideXML(overrideXMLBox.getSelectedObjects() != null);
577 | generator_config.setNeedToStringHashcodeEquals(needToStringHashcodeEqualsBox.getSelectedObjects() != null);
578 | generator_config.setUseSchemaPrefix(useSchemaPrefixBox.getSelectedObjects() != null);
579 | generator_config.setNeedForUpdate(needForUpdateBox.getSelectedObjects() != null);
580 | generator_config.setAnnotationDAO(annotationDAOBox.getSelectedObjects() != null);
581 | generator_config.setUseDAOExtendStyle(useDAOExtendStyleBox.getSelectedObjects() != null);
582 | generator_config.setJsr310Support(jsr310SupportBox.getSelectedObjects() != null);
583 | generator_config.setAnnotation(annotationBox.getSelectedObjects() != null);
584 | generator_config.setUseActualColumnNames(useActualColumnNamesBox.getSelectedObjects() != null);
585 | generator_config.setUseTableNameAlias(useTableNameAliasBox.getSelectedObjects() != null);
586 | generator_config.setUseExample(useExampleBox.getSelectedObjects() != null);
587 | generator_config.setMysql_8(mysql_8Box.getSelectedObjects() != null);
588 |
589 | generator_config.setModelMvnPath(modelMvnField.getText());
590 | generator_config.setDaoMvnPath(daoMvnField.getText());
591 | generator_config.setXmlMvnPath(xmlMvnField.getText());
592 |
593 |
594 | new Generate(generator_config).execute(anActionEvent);
595 | } else {
596 | for (PsiElement psiElement : psiElements) {
597 | TableInfo tableInfo = new TableInfo((DbTable) psiElement);
598 | String tableName = tableInfo.getTableName();
599 | String modelName = StringUtils.dbStringToCamelStyle(tableName);
600 | String primaryKey = "";
601 | if (tableInfo.getPrimaryKeys() != null && tableInfo.getPrimaryKeys().size() != 0) {
602 | primaryKey = tableInfo.getPrimaryKeys().get(0);
603 | }
604 | Config generator_config = new Config();
605 | generator_config.setName(tableName);
606 | generator_config.setTableName(tableName);
607 | generator_config.setProjectFolder(projectFolderBtn.getText());
608 |
609 | generator_config.setModelPackage(modelPackageField.getText());
610 | generator_config.setModelTargetFolder(modelFolderBtn.getText());
611 | generator_config.setDaoPackage(daoPackageField.getText());
612 | generator_config.setDaoTargetFolder(daoFolderBtn.getText());
613 | generator_config.setXmlPackage(xmlPackageField.getText());
614 | generator_config.setXmlTargetFolder(xmlFolderBtn.getText());
615 |
616 | if (this.config != null) {
617 | generator_config.setDaoName(modelName + this.config.getDaoPostfix());
618 | } else {
619 | generator_config.setDaoName(modelName + "Dao");
620 | }
621 | generator_config.setModelName(modelName);
622 | generator_config.setPrimaryKey(primaryKey);
623 |
624 | generator_config.setOffsetLimit(offsetLimitBox.getSelectedObjects() != null);
625 | generator_config.setComment(commentBox.getSelectedObjects() != null);
626 | generator_config.setOverrideXML(overrideXMLBox.getSelectedObjects() != null);
627 | generator_config.setNeedToStringHashcodeEquals(needToStringHashcodeEqualsBox.getSelectedObjects() != null);
628 | generator_config.setUseSchemaPrefix(useSchemaPrefixBox.getSelectedObjects() != null);
629 | generator_config.setNeedForUpdate(needForUpdateBox.getSelectedObjects() != null);
630 | generator_config.setAnnotationDAO(annotationDAOBox.getSelectedObjects() != null);
631 | generator_config.setUseDAOExtendStyle(useDAOExtendStyleBox.getSelectedObjects() != null);
632 | generator_config.setJsr310Support(jsr310SupportBox.getSelectedObjects() != null);
633 | generator_config.setAnnotation(annotationBox.getSelectedObjects() != null);
634 | generator_config.setUseActualColumnNames(useActualColumnNamesBox.getSelectedObjects() != null);
635 | generator_config.setUseTableNameAlias(useTableNameAliasBox.getSelectedObjects() != null);
636 | generator_config.setUseExample(useExampleBox.getSelectedObjects() != null);
637 | generator_config.setMysql_8(mysql_8Box.getSelectedObjects() != null);
638 |
639 | generator_config.setModelMvnPath(modelMvnField.getText());
640 | generator_config.setDaoMvnPath(daoMvnField.getText());
641 | generator_config.setXmlMvnPath(xmlMvnField.getText());
642 |
643 |
644 | new Generate(generator_config).execute(anActionEvent);
645 | }
646 |
647 | }
648 |
649 |
650 | } catch (Exception e1) {
651 | e1.printStackTrace();
652 | } finally {
653 | dispose();
654 | }
655 | }
656 |
657 | private void onCancel() {
658 | dispose();
659 | }
660 | }
661 |
--------------------------------------------------------------------------------
/src/cn/kt/ui/SettingUI.java:
--------------------------------------------------------------------------------
1 | package cn.kt.ui;
2 |
3 | import cn.kt.model.Config;
4 | import cn.kt.setting.PersistentConfig;
5 | import cn.kt.util.JTextFieldHintListener;
6 | import com.intellij.ide.util.PackageChooserDialog;
7 | import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
8 | import com.intellij.openapi.project.Project;
9 | import com.intellij.openapi.ui.TextBrowseFolderListener;
10 | import com.intellij.openapi.ui.TextFieldWithBrowseButton;
11 | import com.intellij.psi.PsiPackage;
12 | import com.intellij.ui.components.JBLabel;
13 | import com.intellij.ui.components.JBPanel;
14 | import com.intellij.ui.components.JBTextField;
15 |
16 | import javax.swing.*;
17 | import javax.swing.border.EmptyBorder;
18 | import java.awt.*;
19 | import java.awt.event.ActionEvent;
20 | import java.util.HashMap;
21 | import java.util.Map;
22 |
23 | /**
24 | * 设置界面
25 | * Created by kangtian on 2018/8/3.
26 | */
27 | public class SettingUI extends JDialog {
28 | public JPanel mainPanel = new JBPanel<>(new GridLayout(2, 1));
29 |
30 |
31 | private JTextField tableNameField = new JTextField(10);
32 | private JBTextField modelPackageField = new JBTextField(12);
33 | private JBTextField daoPackageField = new JBTextField(12);
34 | private JBTextField xmlPackageField = new JBTextField(12);
35 | private JTextField mapperNameField = new JTextField(10);
36 | private JTextField domainNameField = new JTextField(10);
37 | private JTextField keyField = new JTextField(12);
38 |
39 | private TextFieldWithBrowseButton projectFolderBtn = new TextFieldWithBrowseButton();
40 | private TextFieldWithBrowseButton modelFolderBtn = new TextFieldWithBrowseButton();
41 | private TextFieldWithBrowseButton daoFolderBtn = new TextFieldWithBrowseButton();
42 | private TextFieldWithBrowseButton xmlFolderBtn = new TextFieldWithBrowseButton();
43 | private JTextField modelMvnField = new JBTextField(15);
44 | private JTextField daoMvnField = new JBTextField(15);
45 | private JTextField xmlMvnField = new JBTextField(15);
46 | private JButton setProjectBtn = new JButton("Set-Project-Path");
47 |
48 | private JCheckBox offsetLimitBox = new JCheckBox("Page(分页)");
49 | private JCheckBox commentBox = new JCheckBox("comment(实体注释)");
50 | private JCheckBox overrideXMLBox = new JCheckBox("Overwrite-Xml");
51 | private JCheckBox needToStringHashcodeEqualsBox = new JCheckBox("toString/hashCode/equals");
52 | private JCheckBox useSchemaPrefixBox = new JCheckBox("Use-Schema(使用Schema前缀)");
53 | private JCheckBox needForUpdateBox = new JCheckBox("Add-ForUpdate(select增加ForUpdate)");
54 | private JCheckBox annotationDAOBox = new JCheckBox("Repository-Annotation(Repository注解)");
55 | private JCheckBox useDAOExtendStyleBox = new JCheckBox("Parent-Interface(公共父接口)");
56 | private JCheckBox jsr310SupportBox = new JCheckBox("JSR310: Date and Time API");
57 | private JCheckBox annotationBox = new JCheckBox("JPA-Annotation(JPA注解)");
58 | private JCheckBox useActualColumnNamesBox = new JCheckBox("Actual-Column(实际的列名)");
59 | private JCheckBox useTableNameAliasBox = new JCheckBox("Use-Alias(启用别名查询)");
60 | private JCheckBox useExampleBox = new JCheckBox("Use-Example");
61 | private JCheckBox mysql_8Box = new JCheckBox("mysql_8");
62 |
63 | private PersistentConfig config;
64 | public SettingUI() {
65 | setContentPane(mainPanel);
66 | }
67 |
68 |
69 |
70 | public void createUI(Project project) {
71 | String projectFolder = project.getBasePath();
72 | mainPanel.setPreferredSize(new Dimension(0,0));
73 | JPanel paneMainTop = new JPanel(new FlowLayout(FlowLayout.LEFT));
74 |
75 | JPanel paneMainTop1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
76 | JPanel paneMainTop2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
77 | JPanel paneMainTop3 = new JPanel(new GridLayout(4, 1, 3, 3));
78 | paneMainTop.add(paneMainTop1);
79 | paneMainTop.add(paneMainTop2);
80 | paneMainTop.add(paneMainTop3);
81 |
82 | JPanel paneLeft1 = new JPanel();
83 | paneLeft1.setLayout(new FlowLayout(FlowLayout.CENTER));
84 | paneLeft1.add(new JLabel("table name:"));
85 | tableNameField.setText("example: db_table");
86 | tableNameField.setEnabled(false);
87 | paneLeft1.add(tableNameField);
88 |
89 | JPanel paneLeft2 = new JPanel();
90 | paneLeft2.setLayout(new FlowLayout(FlowLayout.CENTER));
91 | paneLeft2.add(new JLabel("primary key:"));
92 | keyField.setText("default primary key");
93 | keyField.setEnabled(false);
94 | paneLeft2.add(keyField);
95 |
96 | JPanel paneRight1 = new JPanel();
97 | paneRight1.setLayout(new FlowLayout(FlowLayout.CENTER));
98 | paneRight1.add(new JLabel("model name:"));
99 | domainNameField.setText("example: dbTable");
100 | domainNameField.setEnabled(false);
101 | paneRight1.add(domainNameField);
102 | JPanel paneRight2 = new JPanel();
103 | paneRight2.setLayout(new FlowLayout(FlowLayout.CENTER));
104 | paneRight2.add(new JLabel("dao postfix:"));
105 | mapperNameField.setText("Dao");
106 | paneRight2.add(mapperNameField);
107 |
108 | paneMainTop1.add(paneLeft1);
109 | paneMainTop1.add(paneLeft2);
110 | paneMainTop1.add(paneRight1);
111 | paneMainTop1.add(paneRight2);
112 |
113 | JPanel modelPackagePanel = new JPanel();
114 | modelPackagePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
115 | JBLabel labelLeft4 = new JBLabel("model package:");
116 | modelPackagePanel.add(labelLeft4);
117 | modelPackagePanel.add(modelPackageField);
118 | JButton packageBtn1 = new JButton("...");
119 | packageBtn1.addActionListener(actionEvent -> {
120 | final PackageChooserDialog chooser = new PackageChooserDialog("chooser model package", project);
121 | chooser.selectPackage(modelPackageField.getText());
122 | chooser.show();
123 | final PsiPackage psiPackage = chooser.getSelectedPackage();
124 | String packageName = psiPackage == null ? null : psiPackage.getQualifiedName();
125 | modelPackageField.setText(packageName);
126 | });
127 | modelPackagePanel.add(packageBtn1);
128 |
129 |
130 | JPanel daoPackagePanel = new JPanel();
131 | daoPackagePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
132 | JLabel labelLeft5 = new JLabel("dao package:");
133 | daoPackagePanel.add(labelLeft5);
134 | daoPackagePanel.add(daoPackageField);
135 |
136 | JButton packageBtn2 = new JButton("...");
137 | packageBtn2.addActionListener(actionEvent -> {
138 | final PackageChooserDialog chooser = new PackageChooserDialog("choose dao package", project);
139 | chooser.selectPackage(daoPackageField.getText());
140 | chooser.show();
141 | final PsiPackage psiPackage = chooser.getSelectedPackage();
142 | String packageName = psiPackage == null ? null : psiPackage.getQualifiedName();
143 | daoPackageField.setText(packageName);
144 | });
145 | daoPackagePanel.add(packageBtn2);
146 |
147 | JPanel xmlPackagePanel = new JPanel();
148 | xmlPackagePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
149 | JLabel labelLeft6 = new JLabel("xml package:");
150 | xmlPackagePanel.add(labelLeft6);
151 | xmlPackagePanel.add(xmlPackageField);
152 |
153 | paneMainTop2.add(modelPackagePanel);
154 | paneMainTop2.add(daoPackagePanel);
155 | paneMainTop2.add(xmlPackagePanel);
156 |
157 |
158 | JPanel projectFolderPanel = new JPanel();
159 | projectFolderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
160 | JLabel projectLabel = new JLabel("project folder:");
161 | projectFolderPanel.add(projectLabel);
162 | projectFolderBtn.setTextFieldPreferredWidth(45);
163 | projectFolderBtn.setText(projectFolder);
164 | projectFolderBtn.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) {
165 | @Override
166 | public void actionPerformed(ActionEvent e) {
167 | super.actionPerformed(e);
168 | projectFolderBtn.setText(projectFolderBtn.getText().replaceAll("\\\\","/"));
169 | }
170 | });
171 | projectFolderPanel.add(projectFolderBtn);
172 | projectFolderPanel.add(setProjectBtn);
173 |
174 |
175 | JPanel modelFolderPanel = new JPanel();
176 | modelFolderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
177 | modelFolderPanel.add(new JLabel("model folder:"));
178 |
179 | modelFolderBtn.setTextFieldPreferredWidth(45);
180 | modelFolderBtn.setText(projectFolder);
181 | modelFolderBtn.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) {
182 | @Override
183 | public void actionPerformed(ActionEvent e) {
184 | super.actionPerformed(e);
185 | modelFolderBtn.setText(modelFolderBtn.getText().replaceAll("\\\\","/"));
186 | }
187 | });
188 | modelFolderPanel.add(modelFolderBtn);
189 | modelFolderPanel.add(new JLabel("mvn path:"));
190 | modelMvnField.setText("src/main/java");
191 | modelFolderPanel.add(modelMvnField);
192 |
193 |
194 | JPanel daoFolderPanel = new JPanel();
195 | daoFolderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
196 | daoFolderPanel.add(new JLabel("dao folder:"));
197 | daoFolderBtn.setTextFieldPreferredWidth(45);
198 | daoFolderBtn.setText(projectFolder);
199 | daoFolderBtn.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) {
200 | @Override
201 | public void actionPerformed(ActionEvent e) {
202 | super.actionPerformed(e);
203 | daoFolderBtn.setText(daoFolderBtn.getText().replaceAll("\\\\","/"));
204 | }
205 | });
206 | daoFolderPanel.add(daoFolderBtn);
207 | daoFolderPanel.add(new JLabel("mvn path:"));
208 | daoMvnField.setText("src/main/java");
209 | daoFolderPanel.add(daoMvnField);
210 |
211 |
212 | JPanel xmlFolderPanel = new JPanel();
213 | xmlFolderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
214 | xmlFolderPanel.add(new JLabel("xml folder:"));
215 |
216 |
217 | xmlFolderBtn.setTextFieldPreferredWidth(45);
218 | xmlFolderBtn.setText(projectFolder);
219 | xmlFolderBtn.addBrowseFolderListener(new TextBrowseFolderListener(FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor()) {});
220 | xmlFolderPanel.add(xmlFolderBtn);
221 | xmlFolderPanel.add(new JLabel("mvn path:"));
222 | xmlMvnField.setText("src/main/resources");
223 | xmlFolderPanel.add(xmlMvnField);
224 |
225 | paneMainTop3.add(projectFolderPanel);
226 | paneMainTop3.add(modelFolderPanel);
227 | paneMainTop3.add(daoFolderPanel);
228 | paneMainTop3.add(xmlFolderPanel);
229 |
230 |
231 | offsetLimitBox.setSelected(true);
232 | commentBox.setSelected(true);
233 | overrideXMLBox.setSelected(true);
234 | needToStringHashcodeEqualsBox.setSelected(true);
235 | useSchemaPrefixBox.setSelected(true);
236 | useExampleBox.setSelected(true);
237 |
238 |
239 | JBPanel paneMainDown = new JBPanel(new GridLayout(5, 5, 5, 5));
240 | paneMainDown.setBorder(new EmptyBorder(2, 80, 100, 40));
241 |
242 | paneMainDown.add(offsetLimitBox);
243 | paneMainDown.add(commentBox);
244 | paneMainDown.add(overrideXMLBox);
245 | paneMainDown.add(needToStringHashcodeEqualsBox);
246 | paneMainDown.add(useSchemaPrefixBox);
247 | paneMainDown.add(needForUpdateBox);
248 | paneMainDown.add(annotationDAOBox);
249 | paneMainDown.add(useDAOExtendStyleBox);
250 | paneMainDown.add(jsr310SupportBox);
251 | paneMainDown.add(annotationBox);
252 | paneMainDown.add(useActualColumnNamesBox);
253 | paneMainDown.add(useTableNameAliasBox);
254 | paneMainDown.add(useExampleBox);
255 | paneMainDown.add(mysql_8Box);
256 |
257 | mainPanel.add(paneMainTop);
258 | mainPanel.add(paneMainDown);
259 |
260 |
261 | config = PersistentConfig.getInstance(project);
262 | Map initConfig = config.getInitConfig();
263 | if (initConfig != null) {
264 | Config config = initConfig.get("initConfig");
265 | mapperNameField.setText(config.getDaoPostfix());
266 | modelPackageField.setText(config.getModelPackage());
267 | daoPackageField.setText(config.getDaoPackage());
268 | xmlPackageField.setText(config.getXmlPackage());
269 |
270 | projectFolderBtn.setText(config.getProjectFolder());
271 | modelFolderBtn.setText(config.getModelTargetFolder());
272 | daoFolderBtn.setText(config.getDaoTargetFolder());
273 | xmlFolderBtn.setText(config.getXmlTargetFolder());
274 |
275 | offsetLimitBox.setSelected(config.isOffsetLimit());
276 | commentBox.setSelected(config.isComment());
277 | overrideXMLBox.setSelected(config.isOverrideXML());
278 | needToStringHashcodeEqualsBox.setSelected(config.isNeedToStringHashcodeEquals());
279 | useSchemaPrefixBox.setSelected(config.isUseSchemaPrefix());
280 | needForUpdateBox.setSelected(config.isNeedForUpdate());
281 | annotationDAOBox.setSelected(config.isAnnotationDAO());
282 | useDAOExtendStyleBox.setSelected(config.isUseDAOExtendStyle());
283 | jsr310SupportBox.setSelected(config.isJsr310Support());
284 | annotationBox.setSelected(config.isAnnotation());
285 | useActualColumnNamesBox.setSelected(config.isUseActualColumnNames());
286 | useTableNameAliasBox.setSelected(config.isUseTableNameAlias());
287 | useExampleBox.setSelected(config.isUseExample());
288 | mysql_8Box.setSelected(config.isMysql_8());
289 | } else {
290 | modelPackageField.addFocusListener(new JTextFieldHintListener(modelPackageField, "generator"));
291 | daoPackageField.addFocusListener(new JTextFieldHintListener(daoPackageField, "generator"));
292 | xmlPackageField.addFocusListener(new JTextFieldHintListener(xmlPackageField, "generator"));
293 | }
294 | }
295 |
296 | public boolean isModified() {
297 | boolean modified = true;
298 | // modified |= !this.id.getText().equals(config.getId());
299 | // modified |= !this.entity.getText().equals(config.getEntity());
300 | // modified |= !this.project_directory.getText().equals(config.getProject_directory());
301 | // modified |= !this.dao_name.getText().equals(config.getDao_name());
302 | //
303 | // modified |= !this.entity_package.getText().equals(config.getEntity_package());
304 | // modified |= !this.entity_directory.getText().equals(config.getEntity_directory());
305 | // modified |= !this.mapper_package.getText().equals(config.getMapper_package());
306 | // modified |= !this.mapper_directory.getText().equals(config.getMapper_directory());
307 | // modified |= !this.xml_package.getText().equals(config.getXml_package());
308 | // modified |= !this.xml_directory.getText().equals(config.getXml_directory());
309 | // modified |= !this.password.getPassword().equals(config.getPassword());
310 | // modified |= !this.username.getText().equals(config.getUsername());
311 | return modified;
312 | }
313 |
314 | public void apply() {
315 | HashMap initConfig = new HashMap<>();
316 | Config config = new Config();
317 | config.setName("initConfig");
318 | config.setDaoPostfix(mapperNameField.getText());
319 | config.setModelPackage(modelPackageField.getText());
320 | config.setDaoPackage(daoPackageField.getText());
321 | config.setXmlPackage(xmlPackageField.getText());
322 | config.setProjectFolder(projectFolderBtn.getText());
323 | config.setModelTargetFolder(modelFolderBtn.getText());
324 | config.setDaoTargetFolder(daoFolderBtn.getText());
325 | config.setXmlTargetFolder(xmlFolderBtn.getText());
326 | config.setOffsetLimit(offsetLimitBox.getSelectedObjects() != null);
327 | config.setComment(commentBox.getSelectedObjects() != null);
328 | config.setOverrideXML(overrideXMLBox.getSelectedObjects() != null);
329 | config.setNeedToStringHashcodeEquals(needToStringHashcodeEqualsBox.getSelectedObjects() != null);
330 | config.setUseSchemaPrefix(useSchemaPrefixBox.getSelectedObjects() != null);
331 | config.setNeedForUpdate(needForUpdateBox.getSelectedObjects() != null);
332 | config.setAnnotationDAO(annotationDAOBox.getSelectedObjects() != null);
333 | config.setUseDAOExtendStyle(useDAOExtendStyleBox.getSelectedObjects() != null);
334 | config.setJsr310Support(jsr310SupportBox.getSelectedObjects() != null);
335 | config.setAnnotation(annotationBox.getSelectedObjects() != null);
336 | config.setUseActualColumnNames(useActualColumnNamesBox.getSelectedObjects() != null);
337 | config.setUseTableNameAlias(useTableNameAliasBox.getSelectedObjects() != null);
338 | config.setUseExample(useExampleBox.getSelectedObjects() != null);
339 | config.setMysql_8(mysql_8Box.getSelectedObjects() != null);
340 |
341 | initConfig.put(config.getName(), config);
342 | this.config.setInitConfig(initConfig);
343 |
344 |
345 | }
346 |
347 | public void reset() {
348 |
349 | }
350 |
351 | @Override
352 | public JPanel getContentPane() {
353 | return mainPanel;
354 | }
355 |
356 |
357 | }
358 |
--------------------------------------------------------------------------------
/src/cn/kt/ui/UserUI.java:
--------------------------------------------------------------------------------
1 | package cn.kt.ui;
2 |
3 | import cn.kt.model.Config;
4 | import cn.kt.model.DbType;
5 | import cn.kt.model.User;
6 | import cn.kt.setting.PersistentConfig;
7 | import com.intellij.credentialStore.CredentialAttributes;
8 | import com.intellij.credentialStore.Credentials;
9 | import com.intellij.ide.passwordSafe.PasswordSafe;
10 | import com.intellij.openapi.actionSystem.AnActionEvent;
11 | import com.intellij.openapi.actionSystem.PlatformDataKeys;
12 | import com.intellij.openapi.project.Project;
13 | import com.intellij.openapi.ui.Messages;
14 | import com.intellij.openapi.vfs.VirtualFile;
15 | import com.intellij.ui.components.JBPanel;
16 | import com.intellij.ui.components.JBTextField;
17 |
18 | import javax.swing.*;
19 | import javax.swing.border.EmptyBorder;
20 | import java.awt.*;
21 | import java.awt.event.*;
22 | import java.sql.Connection;
23 | import java.sql.DriverManager;
24 | import java.util.HashMap;
25 | import java.util.Map;
26 |
27 | /**
28 | * 账号密码输入界面
29 | * Created by kangtian on 2018/8/3.
30 | */
31 | public class UserUI extends JFrame {
32 |
33 | private AnActionEvent anActionEvent;
34 | private Project project;
35 | private PersistentConfig persistentConfig;
36 | private Config config;
37 | private JPanel contentPanel = new JBPanel<>();
38 | private JPanel btnPanel = new JBPanel<>();
39 | private JPanel filedPanel = new JBPanel<>();
40 | private JButton buttonOK = new JButton("ok");
41 | private JButton buttonCancel = new JButton("cancle");
42 |
43 | public JTextField usernameField = new JBTextField(20);
44 | public JTextField passwordField = new JBTextField(20);
45 |
46 |
47 | public UserUI(String driverClass, String address, AnActionEvent anActionEvent, Config config) throws HeadlessException {
48 | this.anActionEvent = anActionEvent;
49 | this.project = anActionEvent.getData(PlatformDataKeys.PROJECT);
50 | this.persistentConfig = PersistentConfig.getInstance(project);
51 | this.config = config;
52 | setTitle("set username and password");
53 | setPreferredSize(new Dimension(400, 180));//设置大小
54 | setLocation(550, 350);
55 | pack();
56 | setVisible(true);
57 | getRootPane().setDefaultButton(buttonOK);
58 | setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
59 | setContentPane(contentPanel);
60 |
61 | filedPanel.setLayout(new GridLayout(2, 1));
62 | filedPanel.setBorder(new EmptyBorder(8, 2, 2, 2));
63 |
64 | JPanel panel1 = new JBPanel<>();
65 | panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
66 | panel1.setBorder(new EmptyBorder(2, 2, 2, 2));
67 |
68 | JPanel panel2 = new JBPanel<>();
69 | panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
70 | panel2.setBorder(new EmptyBorder(2, 2, 2, 2));
71 |
72 | panel1.add(new JLabel("username:"));
73 | panel1.add(usernameField);
74 | panel2.add(new JLabel("password:"));
75 | panel2.add(passwordField);
76 |
77 | filedPanel.add(panel1);
78 | filedPanel.add(panel2);
79 | contentPanel.add(filedPanel);
80 |
81 | btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS));
82 | btnPanel.setBorder(new EmptyBorder(1, 5, 1, 5));
83 | btnPanel.add(buttonOK);
84 | btnPanel.add(buttonCancel);
85 | contentPanel.add(btnPanel);
86 |
87 | buttonOK.addActionListener(new ActionListener() {
88 | public void actionPerformed(ActionEvent e) {
89 | onOK(driverClass, address, persistentConfig, project);
90 | }
91 | });
92 |
93 | buttonCancel.addActionListener(new ActionListener() {
94 | public void actionPerformed(ActionEvent e) {
95 | onCancel();
96 | }
97 | });
98 |
99 | addWindowListener(new WindowAdapter() {
100 | public void windowClosing(WindowEvent e) {
101 | onCancel();
102 | }
103 | });
104 | contentPanel.registerKeyboardAction(new ActionListener() {
105 | public void actionPerformed(ActionEvent e) {
106 | onCancel();
107 | }
108 | }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
109 | }
110 |
111 | private void onOK(String driverClass, String address, PersistentConfig persistentConfig, Project project) {
112 | try {
113 | String originAddress = address;
114 | Connection conn = null;
115 | String DbTypeName = "";
116 | Boolean isMySQL_8 = config.isMysql_8();
117 | try {
118 | if (driverClass.contains("oracle")) {
119 | DbTypeName = "oracle";
120 | Class.forName(DbType.Oracle.getDriverClass());
121 | } else if (driverClass.contains("mysql")) {
122 | DbTypeName = "mysql";
123 | if (!isMySQL_8) {
124 | Class.forName(DbType.MySQL.getDriverClass());
125 | } else {
126 | Class.forName(DbType.MySQL_8.getDriverClass());
127 | }
128 | } else if (driverClass.contains("postgresql")) {
129 | DbTypeName = "postgresql";
130 | Class.forName(DbType.PostgreSQL.getDriverClass());
131 | } else if (driverClass.contains("sqlserver")) {
132 | DbTypeName = "sqlserver";
133 | Class.forName(DbType.SqlServer.getDriverClass());
134 | } else if (driverClass.contains("sqlite")) {
135 | DbTypeName = "sqlite";
136 | Class.forName(DbType.Sqlite.getDriverClass());
137 | } else if (driverClass.contains("mariadb")) {
138 | DbTypeName = "mariadb";
139 | Class.forName(DbType.MariaDB.getDriverClass());
140 | }
141 |
142 | conn = DriverManager.getConnection(address, usernameField.getText(), passwordField.getText());
143 |
144 | } catch (Exception ex) {
145 | Messages.showMessageDialog(project, "Failed to connect to " + DbTypeName + " database,please check username and password,or mysql is version 8?" + isMySQL_8, "Test connection", Messages.getInformationIcon());
146 | // new UserUI(driverClass, address, anActionEvent, config);
147 | return;
148 | } finally {
149 | if (conn != null) {
150 | conn.close();
151 | }
152 | dispose();
153 | }
154 |
155 | Map users = persistentConfig.getUsers();
156 | if (users == null) {
157 | users = new HashMap<>();
158 | }
159 | users.put(originAddress, new User(usernameField.getText()));
160 | CredentialAttributes attributes = new CredentialAttributes("better-mybatis-generator-" + address, usernameField.getText(), this.getClass(), false);
161 | Credentials saveCredentials = new Credentials(attributes.getUserName(), passwordField.getText());
162 | PasswordSafe.getInstance().set(attributes, saveCredentials);
163 |
164 | persistentConfig.setUsers(users);
165 |
166 |
167 | VirtualFile baseDir = project.getBaseDir();
168 | baseDir.refresh(false, true);
169 | new MainUI(anActionEvent);
170 |
171 | } catch (Exception e1) {
172 | e1.printStackTrace();
173 | } finally {
174 | dispose();
175 | }
176 | }
177 |
178 | private void onCancel() {
179 | dispose();
180 | }
181 | }
182 |
--------------------------------------------------------------------------------
/src/cn/kt/util/GeneratorCallback.java:
--------------------------------------------------------------------------------
1 | package cn.kt.util;
2 |
3 | import org.mybatis.generator.api.ProgressCallback;
4 |
5 | /**
6 | * mybatis generator进度回调
7 | * Created by kangtian on 2018/7/17.
8 | */
9 | public class GeneratorCallback implements ProgressCallback {
10 | @Override
11 | public void introspectionStarted(int i) {
12 | }
13 |
14 | @Override
15 | public void generationStarted(int i) {
16 |
17 | }
18 |
19 | @Override
20 | public void saveStarted(int i) {
21 |
22 | }
23 |
24 | @Override
25 | public void startTask(String s) {
26 | System.out.println("startTask" + s);
27 | }
28 |
29 | @Override
30 | public void done() {
31 | }
32 |
33 | @Override
34 | public void checkCancel() throws InterruptedException {
35 |
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/cn/kt/util/JTextFieldHintListener.java:
--------------------------------------------------------------------------------
1 | package cn.kt.util;
2 | import javax.swing.*;
3 | import java.awt.*;
4 | import java.awt.event.FocusEvent;
5 | import java.awt.event.FocusListener;
6 | /**
7 | * 输入框提示
8 | * Created by kangtian on 2018/8/3.
9 | */
10 | public class JTextFieldHintListener implements FocusListener {
11 | private String hintText;
12 | private JTextField textField;
13 | public JTextFieldHintListener(JTextField jTextField,String hintText) {
14 | this.textField = jTextField;
15 | this.hintText = hintText;
16 | jTextField.setText(hintText); //默认直接显示
17 | jTextField.setForeground(Color.GRAY);
18 | }
19 |
20 | @Override
21 | public void focusGained(FocusEvent e) {
22 | //获取焦点时,清空提示内容
23 | String temp = textField.getText();
24 | if(temp.equals(hintText)) {
25 | textField.setText("");
26 | textField.setForeground(Color.BLACK);
27 | }
28 |
29 | }
30 |
31 | @Override
32 | public void focusLost(FocusEvent e) {
33 | //失去焦点时,没有输入内容,显示提示内容
34 | String temp = textField.getText();
35 | if(temp.equals("")) {
36 | textField.setForeground(Color.GRAY);
37 | textField.setText(hintText);
38 | }
39 |
40 | }
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/src/cn/kt/util/StringUtils.java:
--------------------------------------------------------------------------------
1 | package cn.kt.util;
2 |
3 | /**
4 | * Created by Owen on 6/18/16.
5 | */
6 | public class StringUtils {
7 |
8 | /**
9 | *
10 | * convert string from slash style to camel style, such as my_course will convert to MyCourse
11 | *
12 | * @param str
13 | * @return
14 | */
15 | public static String dbStringToCamelStyle(String str) {
16 | if (str != null) {
17 | str = str.toLowerCase();
18 | StringBuilder sb = new StringBuilder();
19 | sb.append(String.valueOf(str.charAt(0)).toUpperCase());
20 | for (int i = 1; i < str.length(); i++) {
21 | char c = str.charAt(i);
22 | if (c != '_') {
23 | sb.append(c);
24 | } else {
25 | if (i + 1 < str.length()) {
26 | sb.append(String.valueOf(str.charAt(i + 1)).toUpperCase());
27 | i++;
28 | }
29 | }
30 | }
31 | return sb.toString();
32 | }
33 | return null;
34 | }
35 | public static boolean isEmpty(Object str) {
36 | return str == null || "".equals(str);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------