├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── TODO.md ├── _config.yml ├── assets └── 1559619424122.jpg ├── pom.xml └── src └── main ├── java └── com │ └── github │ └── zhuyizhuo │ └── generator │ ├── annotation │ ├── CoventionClass.java │ ├── NotNull.java │ ├── Nullable.java │ ├── Resource.java │ └── Value.java │ ├── constants │ ├── ConfigConstants.java │ ├── LinkConstants.java │ └── TemplateConstants.java │ ├── enums │ ├── DbTypeEnums.java │ ├── ErrorTypeEnums.java │ ├── FileTypeEnums.java │ ├── LogLevelEnums.java │ ├── MethodEnums.java │ ├── ModuleTypeEnums.java │ └── TemplateTypeEnums.java │ ├── exception │ └── GeneratorException.java │ ├── mybatis │ ├── convention │ │ ├── ClassCommentInfo.java │ │ └── FileOutPathInfo.java │ ├── database │ │ ├── entity │ │ │ ├── ColumnInfo.java │ │ │ ├── DataBaseInfo.java │ │ │ └── DbTableInfo.java │ │ ├── factory │ │ │ └── DbServiceFactory.java │ │ ├── mapper │ │ │ ├── MysqlDataBaseMapper.java │ │ │ └── OracleDataBaseMapper.java │ │ └── service │ │ │ ├── DbService.java │ │ │ ├── abstracted │ │ │ └── AbstractDbService.java │ │ │ └── impl │ │ │ ├── MysqlDbServiceImpl.java │ │ │ └── OracleDbServiceImpl.java │ ├── dto │ │ ├── JavaClassDefinition.java │ │ ├── JavaColumnInfo.java │ │ ├── MethodDescription.java │ │ └── MybatisXmlDefinition.java │ ├── generator │ │ ├── DefaultGenerator.java │ │ ├── EmptyGenerator.java │ │ ├── Generator.java │ │ ├── GeneratorBuilder.java │ │ ├── extension │ │ │ ├── CustomizeModuleInfo.java │ │ │ ├── FormatService.java │ │ │ ├── JavaModuleInfo.java │ │ │ └── LogService.java │ │ ├── factory │ │ │ └── GenerateServiceFactory.java │ │ ├── service │ │ │ ├── GenerateService.java │ │ │ └── template │ │ │ │ ├── TemplateGenerateService.java │ │ │ │ └── freemarker │ │ │ │ ├── FreemarkerGenerateService.java │ │ │ │ └── impl │ │ │ │ ├── MybatisPlusGenerateImpl.java │ │ │ │ ├── MysqlGenerateImpl.java │ │ │ │ └── OracleGenerateImpl.java │ │ └── support │ │ │ ├── ContextHolder.java │ │ │ ├── MethodInfo.java │ │ │ └── ModuleInfo.java │ └── vo │ │ ├── GenerateInfo.java │ │ ├── GenerateMetaData.java │ │ ├── ModulePathInfo.java │ │ └── TableInfo.java │ └── utils │ ├── CheckUtils.java │ ├── Freemarker.java │ ├── GeneratorStringUtils.java │ ├── LogUtils.java │ ├── PathUtils.java │ ├── PropertiesUtils.java │ ├── SqlSessionUtils.java │ └── TypeConversion.java └── resources ├── freemarker └── template │ ├── java │ ├── common │ │ ├── batchInsert.ftl │ │ ├── countByWhere.ftl │ │ ├── deleteByPrimaryKey.ftl │ │ ├── deleteByWhere.ftl │ │ ├── insert.ftl │ │ ├── model.ftl │ │ ├── model_lombok.ftl │ │ ├── queryByPrimaryKey.ftl │ │ ├── queryByWhere.ftl │ │ ├── updateByPrimaryKey.ftl │ │ └── vo_swagger_lombok.ftl │ ├── mybatis_plus │ │ ├── mapper_mybatis_plus.ftl │ │ ├── model_mybatis_plus.ftl │ │ ├── model_mybatis_plus_lombok.ftl │ │ ├── service_impl_mybatis_plus.ftl │ │ ├── service_mybatis_plus.ftl │ │ └── xml_mybatis_plus.ftl │ ├── no_primary_key_mysql_mapper_template.ftl │ ├── no_primary_key_oracle_mapper_template.ftl │ ├── primary_key_mysql_mapper_template.ftl │ └── primary_key_oracle_mapper_template.ftl │ └── xml │ ├── common │ ├── common_sql_xml.ftl │ ├── count_by_where_xml.ftl │ ├── delete_by_primary_key_xml.ftl │ ├── delete_by_where_xml.ftl │ ├── insert_xml.ftl │ ├── mysql_batch_insert_xml.ftl │ ├── oracle_batch_insert_xml.ftl │ ├── query_by_primary_key_xml.ftl │ ├── query_by_where_xml.ftl │ ├── result_map_xml.ftl │ └── update_by_primary_key_xml.ftl │ ├── no_primary_key_mysql_mybatis_template.ftl │ ├── no_primary_key_oracle_mybatis_template.ftl │ ├── primary_key_mysql_mybatis_template.ftl │ └── primary_key_oracle_mybatis_template.ftl ├── generate-config.properties ├── generator.properties └── mybatis ├── mappers ├── MysqlDataBaseMapper.xml └── OracleDataBaseMapper.xml └── mybatis-config.xml /.gitignore: -------------------------------------------------------------------------------- 1 | # Windows: 2 | Thumbs.db 3 | ehthumbs.db 4 | Desktop.ini 5 | 6 | # My configurations: 7 | *.svn 8 | *.settings 9 | *.project 10 | *.classpath 11 | 12 | # Compiled class file 13 | *.class 14 | 15 | # Log file 16 | *.log 17 | 18 | # BlueJ files 19 | *.ctxt 20 | 21 | # Mobile Tools for Java (J2ME) 22 | .mtj.tmp/ 23 | 24 | # Package Files # 25 | *.jar 26 | *.war 27 | *.nar 28 | *.ear 29 | *.zip 30 | *.tar.gz 31 | *.rar 32 | .idea 33 | JavaAdvanced.iml 34 | 35 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 36 | hs_err_pid* 37 | 38 | .metadata 39 | 40 | * .TMP 41 | * .bak的 42 | * .SWP 43 | local.properties 44 | .loadpath 45 | .recommenders 46 | 47 | 48 | #STS(Spring工具套件) 49 | .springBeans 50 | /target 51 | *.iml 52 | /.idea 53 | .DS_Store -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | sudo: false # faster builds 3 | 4 | jdk: 5 | - oraclejdk12 6 | - openjdk11 7 | - oraclejdk11 8 | - openjdk8 9 | 10 | cache: 11 | directories: 12 | - $HOME/.m2 13 | 14 | install: true 15 | 16 | script: 17 | - travis_wait 30 mvn clean install -DskipTests=true -Dcheckstyle.skip=true -Dmaven.javadoc.skip=true -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | 3 | ## v1.5.0 4 | - 新增 travis-ci.com 自动检测集成 5 | - 增加数据库类型和 org.apache.ibatis.type.JdbcType 的映射 6 | - 改善用户体验/可用性 7 | - 移除 guava 依赖 8 | - 修复添加类型转换未转大写的问题 9 | - 默认将数据库日期类型映射为 LocalDateTime 10 | - 新增支持作为 SpringBoot 子项目中使用 11 | - 增加 timestamp 和 org.apache.ibatis.type.JdbcType.TIMESTAMP 的映射 12 | - 内置 swagger vo 模板 13 | - 内置 mybatis plus 代码模板支持,支持直接生成 mybatis plus 代码模板 14 | - mapper 模板默认方法名简化 15 | - 需新增模板常量类 统一管理所有模板路径 16 | 17 | ## v1.5.1 18 | - 代码优化 19 | - 数据库表无注释情况默认处理为空字符串 20 | - 内置 oracle 数据库字段类型 NCLOB CLOB BLOB NVARCHAR2 转换 21 | - 优化生成类路径配置 支持每个类单独配置生成路径 22 | - 升级 mybatis 版本为 3.5.6, freemarker 版本为 2.3.30 23 | - 新增 lombok 代码模板 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Code-generator 2 | [![Build Status](https://travis-ci.com/zhuyizhuo/code-generator.svg?branch=master)](https://travis-ci.com/zhuyizhuo/code-generator) 3 | [![maven](https://img.shields.io/maven-central/v/com.github.zhuyizhuo/code-generator.svg)](https://search.maven.org/search?q=g:com.github.zhuyizhuo) 4 | [![releases](https://img.shields.io/github/v/release/zhuyizhuo/code-generator.svg)](https://github.com/zhuyizhuo/code-generator/releases) 5 | ![license](https://img.shields.io/github/license/zhuyizhuo/code-generator.svg) 6 | ![stars](https://img.shields.io/github/stars/zhuyizhuo/code-generator) 7 | 8 | ``` 9 | 本项目致力于更简单易用的配置,更轻量快捷的生成代码. 10 | 一键生成 mybatis xml + model + mapper,并可自由扩展. 11 | ``` 12 | 13 | ### 轻量级的代码生成器 14 | 15 | * 简单轻量 16 | * 配置化 17 | * 可扩展 18 | 19 | ### 支持的数据库 20 | 21 | * mysql 22 | * oracle 23 | 24 | ### 所需环境 25 | 26 | * JDK 1.8 + 27 | 28 | ### 在线文档 29 | 30 | - [在线文档](http://zhuyizhuo.online/code-generator-doc/) 31 | 32 | ### 版本号说明 33 | #### 生成器版本号的格式为 X.Y.Z(又称 Major.Minor.Patch),递增的规则为: 34 | 35 | ``` 36 | X 表示主版本号,当 API 的兼容性变化时,X 递增,Y 和 Z 同时设置为 0。 37 | Y 表示次版本号,当增加功能(不影响 API 的兼容性) 或者 API 被标记为 Deprecated 时,Y 递增,同时 Z 设置为 0。 38 | Z 表示修订号,当功能优化或者当做 Bug 修复时(不影响 API 的兼容性),Z 递增。 39 | ``` 40 | 41 | ### 未发布版本使用步骤 42 | 第一步:切换至对应分支,clone 项目至本地 43 | ``` 44 | git clone https://github.com/zhuyizhuo/code-generator.git 45 | ``` 46 | 第二步:进入项目目录执行以下命令,将项目安装至本地 47 | ``` 48 | mvn clean install 49 | ``` 50 | 51 | 第三步:按照 [在线文档](http://zhuyizhuo.online/code-generator-doc/) 使用即可 52 | 53 | ### 订阅更新 54 | 55 | Star [本项目](https://github.com/zhuyizhuo/code-generator),获取最新版本更新. 56 | 57 | ### 联系作者 58 | 59 | ``` 60 | 如果在使用过程中遇到问题或者疑问,或提出改进建议,请联系作者. 61 | 添加请注明来源: code-generator 62 | ``` 63 | 64 | #### 微信: 65 | 66 | ![zhuo-simple_is_happy](assets/1559619424122.jpg) 67 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # 1.5.1 2 | - 代码优化 3 | - 优化 properties 文件加载 4 | 5 | - GeneratorBuilder.addJavaTemplate 方法是否可重命名 见名知意 6 | 7 | - 文档优化 8 | commonMethodNameFormatService 需配合各方法的 name-format 使用 9 | 10 | - 优化自定义生成器的使用 JavaModuleInfo 增加构造器使用 枚举类型 11 | 12 | # 1.6.0 13 | - 集成 slf4j 打印日志 14 | - 支持在模板中直接获取配置文件的配置 15 | - 支持 java 参数传入获取变量 #{xxx} 16 | - 提供 spring-boot starter 版本 17 | - 支持 yaml 配置 18 | - 增加属性,支持生成建表语句 19 | - 如使用自定义模板 可不校验映射 懒加载 -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-architect -------------------------------------------------------------------------------- /assets/1559619424122.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zhuyizhuo/code-generator/e03116a527059085ce74ccab2426bc36df1e7c2d/assets/1559619424122.jpg -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | org.sonatype.oss 6 | oss-parent 7 | 7 8 | 9 | com.github.zhuyizhuo 10 | code-generator 11 | 1.5.1 12 | 代码生成器 13 | 轻量级可扩展代码生成器 14 | http://zhuyizhuo.online/code-generator-doc/ 15 | 2017 16 | 17 | 18 | Apache 2 19 | http://www.apache.org/licenses/LICENSE-2.0.txt 20 | repo 21 | A business-friendly OSS license 22 | 23 | 24 | 25 | 26 | ZhuYiZhuo 27 | ZhuYiZhuo 28 | zhuyizhuo2019@gmail.com 29 | 30 | Developer 31 | 32 | +8 33 | 34 | 35 | 36 | https://github.com/zhuyizhuo/code-generator.git 37 | scm:git:ssh://git@github.com/zhuyizhuo/code-generator.git 38 | https://github.com/zhuyizhuo/code-generator 39 | 40 | 41 | GitHub 42 | https://github.com/zhuyizhuo/code-generator/issues 43 | 44 | 45 | UTF-8 46 | 1.8 47 | 1.8 48 | 49 | 50 | 51 | org.mybatis 52 | mybatis 53 | 3.5.6 54 | 55 | 56 | org.freemarker 57 | freemarker 58 | 2.3.30 59 | 60 | 61 | 62 | 63 | sonatype-nexus-snapshots 64 | OSS Snapshots Repository 65 | https://oss.sonatype.org/content/repositories/snapshots/ 66 | 67 | 68 | sonatype-nexus-staging 69 | OSS Staging Repository 70 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/annotation/CoventionClass.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | *

11 | * 此注解用来标识约定类 12 | * 用此注解配置的类 将会对类中的属性注入配置文件中的对应配置 13 | * 如果类中属性没有配置则赋值默认值 14 | * 15 | * @author zhuo
16 | * @since 1.4.0 17 | */ 18 | @Documented 19 | @Retention(RetentionPolicy.RUNTIME) 20 | @Target({ElementType.TYPE}) 21 | public @interface CoventionClass { 22 | } -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/annotation/NotNull.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * 此注解用来标识 字段 方法属性 参数 不可为空 11 | * 12 | * @author zhuo
13 | * @since 1.4.0 14 | */ 15 | @Documented 16 | @Retention(RetentionPolicy.CLASS) 17 | @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) 18 | public @interface NotNull { 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/annotation/Nullable.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * 此注解用来标识 字段 方法属性 参数 可为空 11 | * 12 | * @author zhuo
13 | * @since 1.4.0 14 | */ 15 | @Documented 16 | @Retention(RetentionPolicy.CLASS) 17 | @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE}) 18 | public @interface Nullable { 19 | } 20 | 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/annotation/Resource.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * 此注解用来标识资源文件 11 | * 12 | * @author zhuo
13 | * @since 1.4.0 14 | */ 15 | @Target(ElementType.TYPE) 16 | @Retention(RetentionPolicy.RUNTIME) 17 | @Documented 18 | public @interface Resource { 19 | 20 | /** 21 | * 标识资源文件配置 22 | * @return 资源文件的配置 key 23 | */ 24 | String value(); 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/annotation/Value.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * 此注解用来标识资源配置 11 | * 12 | * @author zhuo
13 | * @since 1.4.0 14 | */ 15 | @Target(ElementType.FIELD) 16 | @Retention(RetentionPolicy.RUNTIME) 17 | @Documented 18 | public @interface Value { 19 | 20 | /** 21 | * The actual value expression: e.g. "#{systemProperties.myProp}". 22 | * @return 对应 value 的配置 key 23 | */ 24 | String value(); 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/constants/ConfigConstants.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.constants; 2 | 3 | /** 4 | * 常量类
5 | * 6 | * @author zhuo
7 | * @since 1.0 8 | */ 9 | public class ConfigConstants { 10 | public static final String DB_TYPE = "db.type"; 11 | public static final String URL = "db.url"; 12 | public static final String DRIVER = "db.driver"; 13 | public static final String TABLE_SCHEMA = "db.table-schema"; 14 | public static final String USERNAME = "db.username"; 15 | public static final String PASSWORD = "db.password"; 16 | 17 | public static final String GENERATE_TABLES_NAME = "generate.table-names"; 18 | public static final String LOG_LEVEL = "generate.log.level"; 19 | public static final String PARAMETER_TYPE_USE_TYPE_ALIASES = "generate.resources.xml.mybatis.parameter-type.aliases.enabled"; 20 | public static final String TABLE_SEPARATOR = "generate.table.separator"; 21 | public static final String FIELD_SEPARATOR = "generate.table.field.separator"; 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/constants/LinkConstants.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.constants; 2 | 3 | /** 4 | * 链接配置常量 5 | * 6 | * @author zhuo 7 | * @since 1.5.0 8 | */ 9 | public class LinkConstants { 10 | /** issue 地址 */ 11 | public static final String ISSUE_URL = "https://github.com/zhuyizhuo/code-generator/issues"; 12 | /** github 地址 */ 13 | public static final String GITHUB_URL = "https://github.com/zhuyizhuo/code-generator/"; 14 | /** 文档路径 */ 15 | public static final String DOC_URL = "http://zhuyizhuo.online/code-generator-doc/\nGithub: " + GITHUB_URL; 16 | /** 常见问题 */ 17 | public static final String FAQ_DOC_URL = "http://zhuyizhuo.online/code-generator-doc/guide/faq.html"; 18 | /** 快速开始文档路径 */ 19 | public static final String QUICKSTART_DOC_URL = "http://zhuyizhuo.online/code-generator-doc/guide/quickstart.html"; 20 | /** 生成器扩展文档路径 */ 21 | public static final String EXTENSION_DOC_BASE_URL = "http://zhuyizhuo.online/code-generator-doc/guide/extension.html"; 22 | public static final String EXTENSION_DOC_URL_A = EXTENSION_DOC_BASE_URL + "#新增或修改数据库类型和 Java 类型映射"; 23 | public static final String EXTENSION_DOC_URL_B = EXTENSION_DOC_BASE_URL + "#新增或修改数据库类型和 Mybatis JdbcType 映射"; 24 | /** Maven 仓库地址 */ 25 | public static final String MAVEN_REPOSITORY_URL = "https://search.maven.org/search"; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/constants/TemplateConstants.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.constants; 2 | 3 | /** 4 | * 模板常量类 5 | * 6 | * @author zhuo 7 | * @since 1.5.0 8 | */ 9 | public class TemplateConstants { 10 | /** mybatis plus 相关模板*/ 11 | public static final String XML_MYBATIS_PLUS = "/freemarker/template/java/mybatis_plus/xml_mybatis_plus.ftl"; 12 | public static final String MAPPER_MYBATIS_PLUS = "/freemarker/template/java/mybatis_plus/mapper_mybatis_plus.ftl"; 13 | public static final String MODEL_MYBATIS_PLUS = "/freemarker/template/java/mybatis_plus/model_mybatis_plus.ftl"; 14 | public static final String MODEL_MYBATIS_PLUS_LOMBOK = "/freemarker/template/java/mybatis_plus/model_mybatis_plus_lombok.ftl"; 15 | public static final String SERVICE_MYBATIS_PLUS = "/freemarker/template/java/mybatis_plus/service_mybatis_plus.ftl"; 16 | public static final String SERVICE_IMPL_MYBATIS_PLUS = "/freemarker/template/java/mybatis_plus/service_impl_mybatis_plus.ftl"; 17 | 18 | /** mysql 相关模板 */ 19 | public static final String XML_MYSQL_HAS_PRIMARY_KEY = "/freemarker/template/xml/primary_key_mysql_mybatis_template.ftl"; 20 | public static final String XML_MYSQL_NO_PRIMARY_KEY = "/freemarker/template/xml/no_primary_key_mysql_mybatis_template.ftl"; 21 | public static final String MAPPER_MYSQL_HAS_PRIMARY_KEY = "/freemarker/template/java/primary_key_mysql_mapper_template.ftl"; 22 | public static final String MAPPER_MYSQL_NO_PRIMARY_KEY = "/freemarker/template/java/no_primary_key_mysql_mapper_template.ftl"; 23 | 24 | /** oracle 相关模板 */ 25 | public static final String XML_ORACLE_HAS_PRIMARY_KEY = "/freemarker/template/xml/primary_key_oracle_mybatis_template.ftl"; 26 | public static final String XML_ORACLE_NO_PRIMARY_KEY = "/freemarker/template/xml/no_primary_key_oracle_mybatis_template.ftl"; 27 | public static final String MAPPER_ORACLE_HAS_PRIMARY_KEY = "/freemarker/template/java/primary_key_oracle_mapper_template.ftl"; 28 | public static final String MAPPER_ORACLE_NO_PRIMARY_KEY = "/freemarker/template/java/no_primary_key_oracle_mapper_template.ftl"; 29 | 30 | /** 数据对象 model 模板 */ 31 | public static final String MODEL = "/freemarker/template/java/common/model.ftl"; 32 | /** 数据对象 lombok model 模板 */ 33 | public static final String MODEL_LOMBOK = "/freemarker/template/java/common/model_lombok.ftl"; 34 | /** 数据对象 swagger + lombok VO 模板 */ 35 | public static final String VO_SWAGGER_LOMBOK = "/freemarker/template/java/common/vo_swagger_lombok.ftl"; 36 | } -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/enums/DbTypeEnums.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.enums; 2 | 3 | /** 4 | * 数据库类型枚举 5 | * 6 | * @since 1.4.0 7 | */ 8 | public enum DbTypeEnums { 9 | /** mysql 数据库 */ 10 | MYSQL, 11 | /** oracle 数据库 */ 12 | ORACLE, 13 | ; 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/enums/ErrorTypeEnums.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.enums; 2 | 3 | import com.github.zhuyizhuo.generator.constants.LinkConstants; 4 | import com.github.zhuyizhuo.generator.mybatis.generator.GeneratorBuilder; 5 | import org.apache.ibatis.parsing.GenericTokenParser; 6 | import org.apache.ibatis.parsing.TokenHandler; 7 | 8 | /** 9 | * 错误类型枚举 10 | * 11 | * @author zhuo 12 | * @since 1.5.0 13 | */ 14 | public enum ErrorTypeEnums { 15 | /** 初始化配置失败! */ 16 | INIT_CONFIG_ERROR("00001","","初始化配置失败!\n" + 17 | "可点击以下链接查找解决方案:\n" + 18 | "常见问题: " + LinkConstants.FAQ_DOC_URL + "\n" + 19 | "如果没有解决方案, 可提 ISSUE 反馈: " + LinkConstants.ISSUE_URL), 20 | /** 请检查是否添加对应数据库驱动依赖! */ 21 | CHECK_DEPENDENCE("00002","Error setting driver on UnpooledDataSource.","请检查是否添加对应数据库驱动依赖!\n" + 22 | "示例: \n" + 23 | "mysql 8.0.20 依赖: \n" + 24 | "\n" + 25 | " mysql\n" + 26 | " mysql-connector-java\n" + 27 | " 8.0.20\n" + 28 | " \n" + 29 | "oracle ojdbc14 依赖: \n" + 30 | "\n" + 31 | " com.oracle\n" + 32 | " ojdbc14\n" + 33 | " 10.2.0.4.0\n" + 34 | "\n" + 35 | "Maven 官方仓库地址: " + LinkConstants.MAVEN_REPOSITORY_URL + "\n" + 36 | "可点击以下链接查找解决方案:\n" + 37 | "常见问题: " + LinkConstants.FAQ_DOC_URL + "\n" + 38 | "如果没有解决方案, 可提 ISSUE 反馈: " + LinkConstants.ISSUE_URL), 39 | /** 检查数据库配置 */ 40 | CHECK_DATABASE_CONFIG("00003","using password: YES","请检查数据库配置信息是否正确。\n" + 41 | "可点击以下链接查找解决方案:\n" + 42 | "常见问题: " + LinkConstants.FAQ_DOC_URL + "\n" + 43 | "如果没有解决方案, 可提 ISSUE 反馈: " + LinkConstants.ISSUE_URL), 44 | /** 请检查数据库配置信息是否正确 可以设置日志级别查看详细堆栈 */ 45 | ERROR_DATABASE_CONFIG("00004","","请检查数据库配置信息是否正确。\n" + 46 | "可点击以下链接查找解决方案:\n" + 47 | "常见问题: " + LinkConstants.FAQ_DOC_URL + "\n" + 48 | "如果没有解决方案, 可提 ISSUE 反馈: " + LinkConstants.ISSUE_URL), 49 | 50 | 51 | /** 未内置数据库数据类型和 Java 类型的映射关系 */ 52 | NOT_SUPPORT_DB_DATATYPE("10001","","该版本暂未内置数据库[#{dbDataType}]类型和 Java 类型的映射关系!\n" + 53 | "请使用本生成器提供的扩展 API,自行添加数据库[#{dbDataType}]类型和 Java 类型的映射关系。\n " + 54 | "例如 :将 [#{dbDataType}]类型映射为 String 类型如下 : \n" + 55 | "\t new GeneratorBuilder().fieldType2JavaType(\"#{dbDataType}\", String.class).build();\n" + 56 | "@see "+ GeneratorBuilder.class.getName() +".fieldType2JavaType ; \n" + 57 | "详细扩展参考文档: " + LinkConstants.EXTENSION_DOC_URL_A + "\n" + 58 | "如需内置此类型映射,可提 ISSUE : " + LinkConstants.ISSUE_URL), 59 | /** 未内置数据库数据类型和 MYBATIS JDBC_TYPE的映射关系 */ 60 | NOT_SUPPORT_DATATYPE_JDBC_TYPE("10002","","该版本暂未内置数据库[#{dbColmType}]类型和 Mybatis XML 中 JdbcType 的映射关系!\n" + 61 | "请使用本生成器提供的扩展 API,自行添加数据库[#{dbColmType}]类型和和 Mybatis XML 中 JdbcType 的映射关系。\n " + 62 | "例如 :将 [#{dbColmType}]类型映射为 VARCHAR 类型如下 : \n" + 63 | "\t new GeneratorBuilder().fieldType2JdbcType(\"#{dbColmType}\", JdbcType.VARCHAR).build();\n " + 64 | "@see "+ GeneratorBuilder.class.getName() +".fieldType2JdbcType ;\n" + 65 | "详细扩展参考文档: " + LinkConstants.EXTENSION_DOC_URL_B + "\n" + 66 | "如需内置此类型映射,可提 ISSUE : " + LinkConstants.ISSUE_URL), 67 | ; 68 | 69 | private String errorCode; 70 | private String errorMsg; 71 | private String message; 72 | 73 | ErrorTypeEnums(String errorCode, String errorMsg, String message) { 74 | this.errorCode = errorCode; 75 | this.errorMsg = errorMsg; 76 | this.message = message; 77 | } 78 | 79 | public String getErrorMsg() { 80 | return errorMsg; 81 | } 82 | 83 | public String getMessage() { 84 | return "错误码:" + errorCode + ", 错误信息:" + message; 85 | } 86 | 87 | public String getMessage(String replace) { 88 | GenericTokenParser parser = new GenericTokenParser("#{", "}", new TokenHandler() { 89 | @Override 90 | public String handleToken(String content) { 91 | return replace; 92 | } 93 | }); 94 | return "错误码:" + errorCode + ", 错误信息:" + parser.parse(message); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/enums/FileTypeEnums.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.enums; 2 | 3 | /** 4 | * 文件类型枚举 5 | * 2019年5月26日22:14:22 6 | * 7 | * @author zhuo
8 | * @version 1.4.0 9 | */ 10 | public enum FileTypeEnums { 11 | JAVA, 12 | XML, 13 | ; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/enums/LogLevelEnums.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.enums; 2 | 3 | /** 4 | * 日志级别枚举 5 | * 6 | * @since 1.5.0 7 | */ 8 | public enum LogLevelEnums { 9 | /** 打印堆栈 */ 10 | DEBUG(1), 11 | /** 普通日志 */ 12 | INFO(2), 13 | ; 14 | 15 | private int level; 16 | 17 | LogLevelEnums(int level) { 18 | this.level = level; 19 | } 20 | 21 | public int getLevel() { 22 | return level; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/enums/MethodEnums.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.enums; 2 | 3 | /** 4 | * 方法枚举 5 | * 6 | * @author zhuo
7 | * @since 1.4.0 8 | */ 9 | public enum MethodEnums { 10 | /** 新增方法 */ 11 | INSERT("generate.java.method.insert."), 12 | /** 批量新增方法*/ 13 | BATCH_INSERT("generate.java.method.batch-insert."), 14 | /** 删除方法 */ 15 | DELETE_BY_WHERE("generate.java.method.delete-by-where."), 16 | /** 根据主键删除方法 */ 17 | DELETE_BY_PRIMARY_KEY("generate.java.method.delete-by-primary-key."), 18 | /** 根据主键更新方法 */ 19 | UPDATE_BY_PRIMARY_KEY("generate.java.method.update-by-primary-key."), 20 | /** 查询方法 */ 21 | QUERY_BY_WHERE("generate.java.method.query-by-where."), 22 | /** 根据主键查询 */ 23 | QUERY_BY_PRIMARY_KEY("generate.java.method.select-one-by-primary-key."), 24 | /** 查询总数方法 */ 25 | COUNT_BY_WHERE("generate.java.method.count-by-where."), 26 | /** 所有方法 */ 27 | ALL_METHOD 28 | ; 29 | 30 | private String propertiesBaseKey; 31 | 32 | /** 配置是否生成方法 */ 33 | private String propertiesEnabledKey = "enabled"; 34 | /** 方法注释配置 */ 35 | private String methodCommentKey = "comment"; 36 | /** 默认格式化方式 */ 37 | private String methodFormatKey = "name-format"; 38 | 39 | MethodEnums() { 40 | } 41 | 42 | MethodEnums(String propertiesBaseKey) { 43 | this.propertiesBaseKey = propertiesBaseKey; 44 | } 45 | 46 | public String getPropertiesEnabledKey() { 47 | return propertiesBaseKey + propertiesEnabledKey; 48 | } 49 | 50 | public String getMethodCommentKey() { 51 | return propertiesBaseKey + methodCommentKey; 52 | } 53 | 54 | public String getMethodFormatKey() { 55 | return propertiesBaseKey + methodFormatKey; 56 | } 57 | } -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/enums/ModuleTypeEnums.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.enums; 2 | 3 | /** 4 | * 模块类型枚举
5 | * create time: 2020-10-29 08:25:15
6 | * 7 | * @author zhuo
8 | * @since 1.5.0 9 | */ 10 | public enum ModuleTypeEnums { 11 | 12 | /** 控制层 */ 13 | CONTROLLER(FileTypeEnums.JAVA,"generate.java.module.controller","控制层"), 14 | /** 视图对象 */ 15 | VO(FileTypeEnums.JAVA,"generate.java.module.vo","视图对象"), 16 | /** 服务接口 */ 17 | SERVICE(FileTypeEnums.JAVA,"generate.java.module.service","服务接口"), 18 | /** 服务接口实现 */ 19 | SERVICE_IMPL(FileTypeEnums.JAVA,"generate.java.module.service.impl","服务接口实现"), 20 | /** 数据库接口 */ 21 | MAPPER(FileTypeEnums.JAVA,"generate.java.module.mapper","数据库接口"), 22 | /** 数据对象 */ 23 | MODEL(FileTypeEnums.JAVA,"generate.java.module.model","数据对象"), 24 | /** mybatis xml 文件 */ 25 | XML(FileTypeEnums.XML,"generate.resources.xml","mybatis xml 文件"), 26 | ; 27 | 28 | /** 文件类型 */ 29 | private FileTypeEnums fileType; 30 | /** 配置前缀 */ 31 | private String prefix; 32 | /** 模块描述 */ 33 | private String description; 34 | 35 | ModuleTypeEnums(FileTypeEnums typeEnums, String prefix, String description) { 36 | this.fileType = typeEnums; 37 | this.prefix = prefix; 38 | this.description = description; 39 | } 40 | 41 | public FileTypeEnums getFileType() { 42 | return fileType; 43 | } 44 | 45 | public String getPrefix() { 46 | return prefix; 47 | } 48 | public String getDescription() { 49 | return description; 50 | } 51 | 52 | /** 生成文件的文件名格式化配置 */ 53 | private String fileNameFormat = ".name-format"; 54 | /** 生成文件的包路径配置 */ 55 | private String filePackage = ".package"; 56 | /** 生成文件的输出路径 */ 57 | private String outputPath = ".out-put-path"; 58 | 59 | public String getFileNameFormatKey() { 60 | return prefix + fileNameFormat; 61 | } 62 | 63 | public String getFilePackageKey() { 64 | return prefix + filePackage; 65 | } 66 | 67 | public String getOutputPathKey() { 68 | return prefix + outputPath; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/enums/TemplateTypeEnums.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.enums; 2 | 3 | /** 4 | * 模板类型枚举
5 | * 6 | * @author zhuo
7 | * @since 1.5.0 8 | */ 9 | public enum TemplateTypeEnums { 10 | /** mysql数据库 */ 11 | MYSQL, 12 | ORACLE, 13 | MYBATIS_PLUS, 14 | ; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/exception/GeneratorException.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.exception; 2 | 3 | /** 4 | * 自定义生成器异常 5 | * 6 | * @author zhuo 7 | * @since 1.5.0 8 | */ 9 | public class GeneratorException extends RuntimeException{ 10 | 11 | /** 异常信息 */ 12 | private String message; 13 | 14 | public GeneratorException(String message) { 15 | this.message = message; 16 | } 17 | 18 | @Override 19 | public String getMessage() { 20 | return message; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/convention/ClassCommentInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.convention; 2 | 3 | import com.github.zhuyizhuo.generator.annotation.CoventionClass; 4 | import com.github.zhuyizhuo.generator.annotation.Value; 5 | 6 | import java.text.SimpleDateFormat; 7 | import java.util.Date; 8 | 9 | /** 10 | * 类注释 11 | * time: 2018/7/29 16:10 12 | * 13 | * @author zhuo 14 | * @since 1.0 15 | */ 16 | @CoventionClass 17 | public class ClassCommentInfo { 18 | /** 文件创建时版本号 */ 19 | @Value("#{generate.java.comment.since-version}") 20 | private String sinceVersion; 21 | /** 当前版本号 */ 22 | @Value("#{generate.java.comment.current-version}") 23 | private String version; 24 | /** 作者 */ 25 | @Value("#{generate.java.comment.author}") 26 | private String author; 27 | /** 默认生成时间 */ 28 | private String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); 29 | 30 | public String getVersion() { 31 | return version; 32 | } 33 | 34 | public void setVersion(String version) { 35 | this.version = version; 36 | } 37 | 38 | public String getAuthor() { 39 | return author; 40 | } 41 | 42 | public void setAuthor(String author) { 43 | this.author = author; 44 | } 45 | 46 | public String getCreateTime() { 47 | return createTime; 48 | } 49 | 50 | public void setCreateTime(String createTime) { 51 | this.createTime = createTime; 52 | } 53 | 54 | public String getSinceVersion() { 55 | return sinceVersion; 56 | } 57 | 58 | public void setSinceVersion(String sinceVersion) { 59 | this.sinceVersion = sinceVersion; 60 | } 61 | 62 | @Override 63 | public String toString() { 64 | return "ClassCommentInfo{" + 65 | "sinceVersion='" + sinceVersion + '\'' + 66 | ", version='" + version + '\'' + 67 | ", author='" + author + '\'' + 68 | ", createTime='" + createTime + '\'' + 69 | '}'; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/convention/FileOutPathInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.convention; 2 | 3 | import com.github.zhuyizhuo.generator.annotation.CoventionClass; 4 | import com.github.zhuyizhuo.generator.annotation.Value; 5 | import com.github.zhuyizhuo.generator.enums.FileTypeEnums; 6 | import com.github.zhuyizhuo.generator.enums.ModuleTypeEnums; 7 | import com.github.zhuyizhuo.generator.mybatis.dto.JavaClassDefinition; 8 | import com.github.zhuyizhuo.generator.mybatis.generator.extension.CustomizeModuleInfo; 9 | import com.github.zhuyizhuo.generator.mybatis.generator.extension.FormatService; 10 | import com.github.zhuyizhuo.generator.mybatis.generator.extension.JavaModuleInfo; 11 | import com.github.zhuyizhuo.generator.mybatis.generator.support.ContextHolder; 12 | import com.github.zhuyizhuo.generator.mybatis.generator.support.ModuleInfo; 13 | 14 | import java.text.MessageFormat; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | import java.util.Map; 18 | import java.util.concurrent.ConcurrentHashMap; 19 | 20 | /** 21 | * 包路径及文件输出路径信息
22 | * 23 | * @author zhuo
24 | * @since 1.0 25 | */ 26 | @CoventionClass 27 | public class FileOutPathInfo { 28 | 29 | @Value("#{generate.base.out-put-path}") 30 | private String baseOutputPath; 31 | /** true 则生成完整目录 false 则仅生成目录最后一层 */ 32 | @Value("#{generate.java.base.package.enabled}") 33 | private String basePackageEnabled; 34 | 35 | private String tableName; 36 | private String tableNameCamelCase; 37 | /** 38 | * 类名格式化 Service Map 39 | * ModuleType -> 类名格式化 Service 40 | */ 41 | private Map classNameFormatServiceMap; 42 | /** 43 | * 模块类型 -> 模块的格式化信息 44 | * moduleType -> ModuleInfo 45 | */ 46 | private Map moduleInfoMap; 47 | /** 模块信息 */ 48 | private List modules; 49 | /** moduleType -> java 类定义 Map */ 50 | private Map javaClassDefinitionMap; 51 | 52 | /** 53 | * 初始化模块信息 54 | */ 55 | public void init() { 56 | ModuleTypeEnums[] values = ModuleTypeEnums.values(); 57 | String outPutFullPathFormat = ""; 58 | ModuleInfo info; 59 | String filePackage; 60 | String outPutPath; 61 | for (int i = 0; i < values.length; i++) { 62 | ModuleTypeEnums module = values[i]; 63 | filePackage = ContextHolder.getConfig(module.getFilePackageKey()); 64 | outPutPath = ContextHolder.getConfig(module.getOutputPathKey()); 65 | if (FileTypeEnums.JAVA.equals(module.getFileType())){ 66 | if (filePackage.startsWith(".")){ 67 | filePackage = filePackage.substring(1); 68 | } 69 | outPutFullPathFormat = getJavaOutputFullPath(outPutPath); 70 | } else if (FileTypeEnums.XML.equals(module.getFileType())){ 71 | outPutFullPathFormat = getResourcesOutputFullPath(outPutPath); 72 | } 73 | info = new ModuleInfo(); 74 | info.setModuleType(module.name()); 75 | info.setFileType(module.getFileType()); 76 | info.setFileFullPackage(filePackage); 77 | info.setOutPutFullPathFormatPattern(outPutFullPathFormat); 78 | info.setFileNameFormatServie(getFormatService(module)); 79 | info.setFileNameFormatPattern(ContextHolder.getConfig(module.getFileNameFormatKey())); 80 | addModuleInfo(module, info); 81 | } 82 | } 83 | 84 | public void setClassNameFormatServiceMap(Map classNameFormatServieMap) { 85 | this.classNameFormatServiceMap = classNameFormatServieMap; 86 | } 87 | 88 | /** 89 | * 根据路径获取资源文件输出全路径 90 | * @param resourcesOutPutPath 资源文件的输出路径 91 | * @return 资源文件输出全路径 92 | */ 93 | public String getResourcesOutputFullPath(String resourcesOutPutPath) { 94 | String outPutFullPath = resourcesOutPutPath; 95 | if (!"TRUE".equalsIgnoreCase(basePackageEnabled)) { 96 | String tempPath = resourcesOutPutPath.replaceAll("\\\\","/"); 97 | if (tempPath.lastIndexOf("/") != -1){ 98 | tempPath = tempPath.substring(tempPath.lastIndexOf("/") + 1); 99 | } 100 | outPutFullPath = baseOutputPath + "/" + tempPath; 101 | } 102 | return outPutFullPath + "/{0}.xml"; 103 | } 104 | 105 | /*** 106 | * 将路径中的 . 替换为 / ,将路径处理为正常文件路径 107 | * 108 | * @param outPutPath java 文件输出路径 例如 /xxx/src/main/java/com.github.generator 109 | * @return java 文件输出全路径 110 | */ 111 | public String getJavaOutputFullPath(String outPutPath){ 112 | String outPutFullPath = outPutPath; 113 | int packageStart = outPutFullPath.lastIndexOf(">"); 114 | if(packageStart != -1){ 115 | String basePath = outPutFullPath.substring(0, packageStart); 116 | String fullPackage = outPutFullPath.substring(packageStart + 1); 117 | if (fullPackage.contains(".")){ 118 | outPutFullPath = basePath + fullPackage.replaceAll("\\.", "/"); 119 | } 120 | } 121 | 122 | if (!"TRUE".equalsIgnoreCase(basePackageEnabled)) { 123 | if(outPutFullPath.lastIndexOf("/") != -1){ 124 | outPutFullPath = outPutFullPath.substring(outPutFullPath.lastIndexOf("/") + 1); 125 | } 126 | outPutFullPath = baseOutputPath + "/" + outPutFullPath; 127 | } 128 | return outPutFullPath + "/{0}.java"; 129 | } 130 | 131 | /** 132 | * 初始化类名 及 输出全路径 133 | * @param tableName 表名 134 | * @param tableNameCamelCase 表名驼峰命名 135 | */ 136 | public void initFileNamesAndOutPutFullPath(String tableName, String tableNameCamelCase) { 137 | this.tableName = tableName; 138 | this.tableNameCamelCase = tableNameCamelCase; 139 | 140 | String fileName = ""; 141 | this.modules = new ArrayList<>(); 142 | this.javaClassDefinitionMap = new ConcurrentHashMap<>(); 143 | for (Map.Entry entry : moduleInfoMap.entrySet()) { 144 | String moduleType = entry.getKey(); 145 | ModuleInfo moduleInfo = entry.getValue(); 146 | FormatService fileNameFormatServie = moduleInfo.getFileNameFormatServie(); 147 | if (fileNameFormatServie != null) { 148 | fileName = fileNameFormatServie.format(tableName); 149 | } else { 150 | fileName = fileNameFormat(moduleInfo.getFileType(), moduleInfo.getFileNameFormatPattern()); 151 | } 152 | 153 | if (FileTypeEnums.JAVA.equals(moduleInfo.getFileType())){ 154 | String fileFullPackage = moduleInfo.getFileFullPackage(); 155 | this.javaClassDefinitionMap.put(moduleType, new JavaClassDefinition(fileFullPackage, fileName)); 156 | } 157 | // 设置文件输出全路径 158 | moduleInfo.setOutPutFullPathByFileName(fileName); 159 | this.modules.add(moduleInfo); 160 | } 161 | } 162 | 163 | /** 164 | * 新增 java 模板 165 | * @param fileInfo java 模块信息 166 | */ 167 | public void addJavaTemplate(JavaModuleInfo fileInfo) { 168 | ModuleInfo moduleInfo = getModuleInfo(fileInfo.getModuleType()); 169 | if (moduleInfo == null){ 170 | moduleInfo = new ModuleInfo(); 171 | addModuleInfo(fileInfo.getModuleType(), moduleInfo); 172 | } 173 | String outPutFullPathFormat = getJavaOutputFullPath(fileInfo.getOutputPath()); 174 | moduleInfo.setModuleType(fileInfo.getModuleType()); 175 | moduleInfo.setOutPutFullPathFormatPattern(outPutFullPathFormat); 176 | // 仅 java 模块需设置包路径 177 | moduleInfo.setFileFullPackage(fileInfo.getClassPackage()); 178 | moduleInfo.setFileNameFormatServie(getFormatService(fileInfo.getModuleType())); 179 | moduleInfo.setFileType(FileTypeEnums.JAVA); 180 | moduleInfo.setFileNameFormatPattern(fileInfo.getClassNameFormat()); 181 | } 182 | 183 | /** 184 | * 新增自定义模块模板 185 | * @param fileInfo 自定义模块信息 186 | */ 187 | public void addCustomizeModule(CustomizeModuleInfo fileInfo) { 188 | ModuleInfo moduleInfo = getModuleInfo(fileInfo.getModuleType()); 189 | if (moduleInfo == null){ 190 | moduleInfo = new ModuleInfo(); 191 | addModuleInfo(fileInfo.getModuleType(), moduleInfo); 192 | } 193 | 194 | moduleInfo.setModuleType(fileInfo.getModuleType()); 195 | moduleInfo.setFileNameFormatPattern(fileInfo.getFileNameFormatPattern()); 196 | moduleInfo.setFileNameFormatServie(getFormatService(fileInfo.getModuleType())); 197 | moduleInfo.setOutPutFullPathFormatPattern(fileInfo.getOutPutFullPathFormatPattern()); 198 | } 199 | 200 | /** 201 | * 获取所有模块信息 202 | * @return 所有模块信息 203 | */ 204 | public List getAllModule(){ 205 | return this.modules; 206 | } 207 | 208 | public Map getJavaClassDefinitionMap(){ 209 | return this.javaClassDefinitionMap; 210 | } 211 | 212 | public void setBasePackageEnabled(String basePackageEnabled) { 213 | this.basePackageEnabled = basePackageEnabled; 214 | } 215 | 216 | public void setBaseOutputPath(String baseOutputPath) { 217 | this.baseOutputPath = baseOutputPath; 218 | } 219 | 220 | private void addModuleInfo(ModuleTypeEnums value, ModuleInfo info) { 221 | addModuleInfo(value.toString(), info); 222 | } 223 | 224 | private void addModuleInfo(String moduleType, ModuleInfo info) { 225 | if (this.moduleInfoMap == null){ 226 | this.moduleInfoMap = new ConcurrentHashMap<>(); 227 | } 228 | this.moduleInfoMap.put(moduleType, info); 229 | } 230 | 231 | private ModuleInfo getModuleInfo(String moduleType) { 232 | return this.moduleInfoMap.get(moduleType); 233 | } 234 | 235 | /** 236 | * 格式化类名 237 | */ 238 | private String fileNameFormat(FileTypeEnums typeEnums,String formatConfig) { 239 | if (FileTypeEnums.XML.equals(typeEnums)){ 240 | return MessageFormat.format(formatConfig, tableName.toLowerCase()); 241 | } 242 | return MessageFormat.format(formatConfig, tableNameCamelCase); 243 | } 244 | 245 | private FormatService getFormatService(ModuleTypeEnums moduleType) { 246 | return getFormatService(moduleType.toString()); 247 | } 248 | 249 | private FormatService getFormatService(String moduleType) { 250 | return classNameFormatServiceMap == null ? null : classNameFormatServiceMap.get(moduleType); 251 | } 252 | } -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/entity/ColumnInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.entity; 2 | 3 | /** 4 | * 字段实体
5 | * time 2018/7/27 21:43
6 | * @author zhuo
7 | * @version 1.0 8 | */ 9 | public class ColumnInfo { 10 | /** 列名 */ 11 | private String columnName; 12 | /** 数据库字段类型 */ 13 | private String dataType; 14 | /** 字段备注 */ 15 | private String columnComment; 16 | /** 是否主键 */ 17 | private boolean primaryKey; 18 | 19 | public ColumnInfo() { 20 | } 21 | 22 | public String getColumnName() { 23 | return columnName; 24 | } 25 | 26 | public void setColumnName(String columnName) { 27 | this.columnName = columnName; 28 | } 29 | 30 | public String getDataType() { 31 | return dataType; 32 | } 33 | 34 | public void setDataType(String dataType) { 35 | this.dataType = dataType; 36 | } 37 | 38 | public String getColumnComment() { 39 | return columnComment; 40 | } 41 | 42 | public void setColumnComment(String columnComment) { 43 | this.columnComment = columnComment; 44 | } 45 | 46 | public boolean isPrimaryKey() { 47 | return primaryKey; 48 | } 49 | 50 | public void setPrimaryKey(boolean primaryKey) { 51 | this.primaryKey = primaryKey; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return "ColumnInfo{" + 57 | "columnName='" + columnName + '\'' + 58 | ", dataType='" + dataType + '\'' + 59 | ", columnComment='" + columnComment + '\'' + 60 | ", primaryKey=" + primaryKey + 61 | '}'; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/entity/DataBaseInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.entity; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * 表信息 7 | * @author zhuo 8 | * @version 1.0 9 | * time: 2018/7/29 19:16 10 | */ 11 | public class DataBaseInfo { 12 | /** 数据库名称 */ 13 | private String tableSchema; 14 | /** 表名 */ 15 | private List tableNames; 16 | 17 | public String getTableSchema() { 18 | return tableSchema; 19 | } 20 | 21 | public void setTableSchema(String tableSchema) { 22 | this.tableSchema = tableSchema; 23 | } 24 | 25 | public List getTableNames() { 26 | return tableNames; 27 | } 28 | 29 | public void setTableNames(List tableNames) { 30 | this.tableNames = tableNames; 31 | } 32 | 33 | @Override 34 | public String toString() { 35 | return "{" + 36 | "tableSchema=[" + tableSchema + ']' + 37 | ", tableNames=" + tableNames + 38 | '}'; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/entity/DbTableInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.entity; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 数据库实体 8 | * 2018-7-27 21:15:01 9 | * @author zhuo 10 | * @version 1.0 11 | */ 12 | public class DbTableInfo { 13 | /** 数据库名称 */ 14 | private String tableSchema; 15 | /** 表名 */ 16 | private String tableName; 17 | /** 表注释 */ 18 | private String tableComment; 19 | /** 表字段 */ 20 | private List columnLists = new ArrayList<>(); 21 | 22 | public String getTableSchema() { 23 | return tableSchema; 24 | } 25 | 26 | public void setTableSchema(String tableSchema) { 27 | this.tableSchema = tableSchema; 28 | } 29 | 30 | public String getTableName() { 31 | return tableName; 32 | } 33 | 34 | public void setTableName(String tableName) { 35 | this.tableName = tableName; 36 | } 37 | 38 | public String getTableComment() { 39 | return tableComment; 40 | } 41 | 42 | public void setTableComment(String tableComment) { 43 | this.tableComment = tableComment; 44 | } 45 | 46 | public List getColumnLists() { 47 | return columnLists; 48 | } 49 | 50 | public void setColumnLists(List columnLists) { 51 | this.columnLists = columnLists; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return "DbTableInfo{" + 57 | "tableSchema='" + tableSchema + '\'' + 58 | ", tableName='" + tableName + '\'' + 59 | ", tableComment='" + tableComment + '\'' + 60 | columnLists 61 | +'}'; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/factory/DbServiceFactory.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.factory; 2 | 3 | import com.github.zhuyizhuo.generator.constants.ConfigConstants; 4 | import com.github.zhuyizhuo.generator.enums.DbTypeEnums; 5 | import com.github.zhuyizhuo.generator.mybatis.database.service.DbService; 6 | import com.github.zhuyizhuo.generator.mybatis.database.service.impl.MysqlDbServiceImpl; 7 | import com.github.zhuyizhuo.generator.mybatis.database.service.impl.OracleDbServiceImpl; 8 | import com.github.zhuyizhuo.generator.mybatis.generator.support.ContextHolder; 9 | import com.github.zhuyizhuo.generator.utils.LogUtils; 10 | 11 | import java.util.Map; 12 | import java.util.concurrent.ConcurrentHashMap; 13 | 14 | /** 15 | * 数据库service构建工厂
16 | * time: 2018/7/30 12:57 17 | * 18 | * @author zhuo
19 | * @version 1.0 20 | */ 21 | public class DbServiceFactory { 22 | 23 | private static Map serviceMap = new ConcurrentHashMap(); 24 | 25 | static{ 26 | serviceMap.put(DbTypeEnums.MYSQL.toString(), new MysqlDbServiceImpl()); 27 | serviceMap.put(DbTypeEnums.ORACLE.toString(), new OracleDbServiceImpl()); 28 | } 29 | 30 | public static DbService getDbService() { 31 | String dbType = ContextHolder.getConfig(ConfigConstants.DB_TYPE).toUpperCase(); 32 | LogUtils.info("数据库类型:" + dbType); 33 | DbService dbService = serviceMap.get(dbType); 34 | if (dbService == null){ 35 | String errorMsg = ConfigConstants.DB_TYPE + "配置类型不支持,所支持类型请参照 " + DbTypeEnums.class.getName(); 36 | LogUtils.error(errorMsg); 37 | throw new RuntimeException(errorMsg); 38 | } 39 | return dbService; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/mapper/MysqlDataBaseMapper.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.mapper; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.database.entity.ColumnInfo; 4 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DataBaseInfo; 5 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DbTableInfo; 6 | 7 | import java.util.List; 8 | 9 | /** 10 | * mysql 数据库 mapper 11 | * @author zhuo 12 | * @version 1.0 13 | * time: 2018/7/27 20:55 14 | */ 15 | public interface MysqlDataBaseMapper { 16 | /*** 17 | * 根据表空间和表名查询所有的表信息 18 | * @param schema 查询参数对象 19 | * @return 所有表信息 20 | */ 21 | List getTableNameListBySchema(DataBaseInfo schema); 22 | 23 | /*** 24 | * 根据表信息查询所有列信息 25 | * @param schema 查询参数对象 26 | * @return 所有表和对应列信息 27 | */ 28 | List getColumnListByTableName(DbTableInfo schema); 29 | 30 | /** 31 | * 根据表信息查询主键信息 32 | * @param schema 查询参数对象 33 | * @return 所有的主键信息 34 | */ 35 | List getPrimaryKeys(DbTableInfo schema); 36 | } 37 | 38 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/mapper/OracleDataBaseMapper.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.mapper; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.database.entity.ColumnInfo; 4 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DataBaseInfo; 5 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DbTableInfo; 6 | import org.apache.ibatis.annotations.Param; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * oracle 数据库 mapper 12 | * @author zhuo 13 | * @version 1.0 14 | * time: 2018/7/27 20:55 15 | */ 16 | public interface OracleDataBaseMapper { 17 | /*** 18 | * 根据表空间和表名查询所有的表信息 19 | * @param schema 查询参数对象 20 | * @return 所有表信息 21 | */ 22 | List getTableNameListBySchema(DataBaseInfo schema); 23 | 24 | /** 25 | * 根据表信息查询所有列信息 26 | * @param tableSchema 表空间 27 | * @param tableName 表名 28 | * @return 所有表和对应列信息 29 | */ 30 | DbTableInfo getAllColumnsByTable(@Param("tableSchema") String tableSchema, @Param("tableName") String tableName); 31 | 32 | /** 33 | * 根据表信息查询主键信息 34 | * @param schema 查询主键参数对象 35 | * @return 所有主键信息 36 | */ 37 | List getPrimaryKeys(DbTableInfo schema); 38 | } 39 | 40 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/service/DbService.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.service; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.vo.TableInfo; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * 数据库抽象接口
9 | * time: 2018/7/30 12:56 10 | * 11 | * @author zhuo
12 | * @version 1.0 13 | */ 14 | public interface DbService { 15 | 16 | /** 17 | * 查询数据库表信息及列信息 18 | * @return 数据库表信息 list 19 | */ 20 | List getTableColumns(); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/service/abstracted/AbstractDbService.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.service.abstracted; 2 | 3 | import com.github.zhuyizhuo.generator.constants.ConfigConstants; 4 | import com.github.zhuyizhuo.generator.mybatis.database.entity.ColumnInfo; 5 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DataBaseInfo; 6 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DbTableInfo; 7 | import com.github.zhuyizhuo.generator.mybatis.database.service.DbService; 8 | import com.github.zhuyizhuo.generator.mybatis.dto.JavaColumnInfo; 9 | import com.github.zhuyizhuo.generator.mybatis.generator.support.ContextHolder; 10 | import com.github.zhuyizhuo.generator.mybatis.vo.TableInfo; 11 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 12 | import com.github.zhuyizhuo.generator.utils.TypeConversion; 13 | 14 | import java.util.Arrays; 15 | import java.util.List; 16 | 17 | /** 18 | * 关系型数据库抽象类
19 | * time: 2018/7/30 13:12 20 | * 21 | * @author zhuo
22 | * @version 1.0 23 | */ 24 | public abstract class AbstractDbService implements DbService { 25 | 26 | protected DataBaseInfo getDataBaseInfo() { 27 | DataBaseInfo tableInfo = new DataBaseInfo(); 28 | tableInfo.setTableSchema(getTableSchema()); 29 | tableInfo.setTableNames(getTableNames()); 30 | return tableInfo; 31 | } 32 | 33 | protected String getTableSchema() { 34 | return ContextHolder.getConfig(ConfigConstants.TABLE_SCHEMA); 35 | } 36 | 37 | protected List getTableNames() { 38 | String includeTableName = ContextHolder.getConfig(ConfigConstants.GENERATE_TABLES_NAME); 39 | if (GeneratorStringUtils.isNotBlank(includeTableName)){ 40 | return Arrays.asList(includeTableName.split(",")); 41 | } 42 | return null; 43 | } 44 | 45 | /** 46 | * 将表信息处理成 java 信息 47 | * @param sourceTableInfo 数据库表信息 48 | * @param targetTableInfo 生成器所需的 java 对象 49 | */ 50 | protected void setTableInfo(DbTableInfo sourceTableInfo, TableInfo targetTableInfo) { 51 | 52 | targetTableInfo.setTableName(sourceTableInfo.getTableName()); 53 | targetTableInfo.setTableSchema(sourceTableInfo.getTableSchema()); 54 | targetTableInfo.setTableComment(sourceTableInfo.getTableComment() == null ? "" : sourceTableInfo.getTableComment()); 55 | List columnLists = sourceTableInfo.getColumnLists(); 56 | JavaColumnInfo javaColumnInfo; 57 | for (int i = 0; i < columnLists.size(); i++) { 58 | ColumnInfo columnInfo = columnLists.get(i); 59 | javaColumnInfo = new JavaColumnInfo(); 60 | javaColumnInfo.setDataType(getDataType(columnInfo.getDataType())); 61 | javaColumnInfo.setColumnName(columnInfo.getColumnName()); 62 | javaColumnInfo.setColumnComment(replaceEnter(columnInfo.getColumnComment())); 63 | javaColumnInfo.setJavaColumnName(GeneratorStringUtils 64 | .changeColmName2CamelFirstLower(columnInfo.getColumnName(), ContextHolder.getConfig(ConfigConstants.FIELD_SEPARATOR))); 65 | javaColumnInfo.setJavaDataType(getJavaDataType(columnInfo)); 66 | /** 设置类全路径 java.lang包下的类不需要import */ 67 | javaColumnInfo.setJavaDataTypeFullPath(TypeConversion.javaDataTypeFullPathMap.get(javaColumnInfo.getJavaDataType())); 68 | targetTableInfo.addJavaColumnInfo(javaColumnInfo); 69 | targetTableInfo.addImportPackage(javaColumnInfo.getJavaDataTypeFullPath()); 70 | } 71 | } 72 | 73 | protected String getDataType(String dataType) { 74 | if (GeneratorStringUtils.isNotBlank(dataType) && dataType.contains("TIMESTAMP")){ 75 | return "TIMESTAMP"; 76 | } 77 | return dataType; 78 | } 79 | 80 | protected abstract String getJavaDataType(ColumnInfo columnInfo); 81 | 82 | /** 83 | * 备注去除回车换行 84 | * @param columnComment 字段备注 85 | * @return 去除回车换行后返回 86 | */ 87 | protected String replaceEnter(String columnComment) { 88 | if (GeneratorStringUtils.isBlank(columnComment)) { 89 | return ""; 90 | } 91 | return columnComment.replaceAll("\r"," ").replaceAll("\n"," ").replaceAll("\r\n"," "); 92 | } 93 | 94 | /** 95 | * 数据库表名根据分隔符转为驼峰命名 96 | * @param tableName 数据库表名 97 | * @return 驼峰命名 98 | */ 99 | protected String changeTableNameCamelCase(String tableName) { 100 | return GeneratorStringUtils.changeTableName2CamelFirstUpper(tableName, ContextHolder.getConfig(ConfigConstants.TABLE_SEPARATOR)); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/service/impl/MysqlDbServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.service.impl; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.database.entity.ColumnInfo; 4 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DataBaseInfo; 5 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DbTableInfo; 6 | import com.github.zhuyizhuo.generator.mybatis.database.mapper.MysqlDataBaseMapper; 7 | import com.github.zhuyizhuo.generator.mybatis.database.service.abstracted.AbstractDbService; 8 | import com.github.zhuyizhuo.generator.mybatis.vo.TableInfo; 9 | import com.github.zhuyizhuo.generator.utils.LogUtils; 10 | import com.github.zhuyizhuo.generator.utils.SqlSessionUtils; 11 | import com.github.zhuyizhuo.generator.utils.TypeConversion; 12 | import org.apache.ibatis.session.SqlSession; 13 | 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | /** 18 | * mysql 数据库查询表结构实现
19 | * time: 2018/7/30 13:10 20 | * 21 | * @author zhuo
22 | * @version 1.0 23 | */ 24 | public class MysqlDbServiceImpl extends AbstractDbService { 25 | 26 | @Override 27 | public List getTableColumns() { 28 | SqlSession sqlSession = SqlSessionUtils.getSqlSession(); 29 | MysqlDataBaseMapper mapper = sqlSession.getMapper(MysqlDataBaseMapper.class); 30 | DataBaseInfo dataBaseInfo = getDataBaseInfo(); 31 | List tableList = mapper.getTableNameListBySchema(dataBaseInfo); 32 | LogUtils.info("DataBaseInfo:" + dataBaseInfo +",共查询出" + tableList.size() + "张表."); 33 | 34 | List tableColumns = getTableColumns(mapper, tableList); 35 | sqlSession.close(); 36 | return tableColumns; 37 | } 38 | 39 | private List getTableColumns(MysqlDataBaseMapper mapper, List tableList) { 40 | List lists = new ArrayList<>(); 41 | TableInfo tableInfo = null; 42 | for (int i = 0; i < tableList.size(); i++) { 43 | tableInfo = new TableInfo(); 44 | DbTableInfo dbTableInfo = tableList.get(i); 45 | dbTableInfo.setColumnLists(getColumnInfos(mapper, dbTableInfo)); 46 | //设置值 47 | setTableInfo(dbTableInfo,tableInfo); 48 | tableInfo.setTableNameCamelCase(changeTableNameCamelCase(dbTableInfo.getTableName())); 49 | tableInfo.addPrimaryKeyColumn(getPrimaryKeys(mapper,dbTableInfo)); 50 | lists.add(tableInfo); 51 | } 52 | return lists; 53 | } 54 | 55 | private List getPrimaryKeys(MysqlDataBaseMapper mapper, DbTableInfo dbTableInfo) { 56 | return mapper.getPrimaryKeys(dbTableInfo); 57 | } 58 | 59 | private List getColumnInfos(MysqlDataBaseMapper mapper, DbTableInfo dbTableInfo) { 60 | return mapper.getColumnListByTableName(dbTableInfo); 61 | } 62 | 63 | @Override 64 | protected String getJavaDataType(ColumnInfo columnInfo) { 65 | return TypeConversion.getJavaTypeByDBDataType(columnInfo.getDataType()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/database/service/impl/OracleDbServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.database.service.impl; 2 | 3 | import com.github.zhuyizhuo.generator.constants.ConfigConstants; 4 | import com.github.zhuyizhuo.generator.mybatis.database.entity.ColumnInfo; 5 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DataBaseInfo; 6 | import com.github.zhuyizhuo.generator.mybatis.database.entity.DbTableInfo; 7 | import com.github.zhuyizhuo.generator.mybatis.database.mapper.OracleDataBaseMapper; 8 | import com.github.zhuyizhuo.generator.mybatis.database.service.abstracted.AbstractDbService; 9 | import com.github.zhuyizhuo.generator.mybatis.vo.TableInfo; 10 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 11 | import com.github.zhuyizhuo.generator.utils.LogUtils; 12 | import com.github.zhuyizhuo.generator.utils.PropertiesUtils; 13 | import com.github.zhuyizhuo.generator.utils.SqlSessionUtils; 14 | import com.github.zhuyizhuo.generator.utils.TypeConversion; 15 | import org.apache.ibatis.session.SqlSession; 16 | 17 | import java.util.ArrayList; 18 | import java.util.Arrays; 19 | import java.util.List; 20 | 21 | /** 22 | * oracle 数据库查询表结构实现
23 | * time: 2018/8/6 12:58 24 | * 25 | * @author zhuo
26 | * @version 1.0 27 | */ 28 | public class OracleDbServiceImpl extends AbstractDbService { 29 | 30 | @Override 31 | protected String getTableSchema() { 32 | String tableSchema = super.getTableSchema(); 33 | if (GeneratorStringUtils.isNotBlank(tableSchema)){ 34 | return tableSchema.toUpperCase(); 35 | } 36 | return tableSchema; 37 | } 38 | 39 | @Override 40 | protected List getTableNames() { 41 | String includeTableName = PropertiesUtils.getProperties(ConfigConstants.GENERATE_TABLES_NAME); 42 | if (GeneratorStringUtils.isNotBlank(includeTableName)){ 43 | return Arrays.asList(includeTableName.toUpperCase().split(",")); 44 | } 45 | return null; 46 | } 47 | 48 | @Override 49 | public List getTableColumns() { 50 | SqlSession sqlSession = SqlSessionUtils.getSqlSession(); 51 | OracleDataBaseMapper mapper = sqlSession.getMapper(OracleDataBaseMapper.class); 52 | DataBaseInfo dataBaseInfo = getDataBaseInfo(); 53 | List tableList = mapper.getTableNameListBySchema(dataBaseInfo); 54 | LogUtils.info("共查询出" + tableList.size() + "张表."); 55 | List tableInfos = getTableInfos(mapper, tableList); 56 | sqlSession.close(); 57 | return tableInfos; 58 | } 59 | 60 | private List getTableInfos(OracleDataBaseMapper mapper, List tableList) { 61 | List tableInfos = new ArrayList<>(); 62 | TableInfo tableInfo = null; 63 | for (int i = 0; i < tableList.size(); i++) { 64 | DbTableInfo dbTableInfo = tableList.get(i); 65 | String tableName = dbTableInfo.getTableName(); 66 | DbTableInfo allColumnsByTable = mapper.getAllColumnsByTable(dbTableInfo.getTableSchema(), tableName); 67 | tableInfo = new TableInfo(); 68 | setTableInfo(allColumnsByTable,tableInfo); 69 | tableInfo.setTableNameCamelCase(changeTableNameCamelCase(tableName)); 70 | tableInfo.addPrimaryKeyColumn(getPrimaryKeys(mapper,dbTableInfo)); 71 | tableInfos.add(tableInfo); 72 | } 73 | return tableInfos; 74 | } 75 | 76 | private List getPrimaryKeys(OracleDataBaseMapper mapper, DbTableInfo dbTableInfo) { 77 | return mapper.getPrimaryKeys(dbTableInfo); 78 | } 79 | 80 | @Override 81 | protected String getJavaDataType(ColumnInfo columnInfo) { 82 | return TypeConversion.getJavaTypeByDBDataType(getDataType(columnInfo.getDataType())); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/dto/JavaClassDefinition.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.dto; 2 | 3 | /** 4 | * java 类定义
5 | * time: 2019/5/23 6 | * 7 | * @author zhuo
8 | * @since 1.4.0 9 | */ 10 | public class JavaClassDefinition { 11 | /** 包路径 */ 12 | private String fullPackage; 13 | /** 类名 */ 14 | private String className; 15 | 16 | public JavaClassDefinition() { 17 | } 18 | 19 | public JavaClassDefinition(String fullPackage, String className) { 20 | this.fullPackage = fullPackage; 21 | this.className = className; 22 | } 23 | 24 | public String getFullPackage() { 25 | return fullPackage; 26 | } 27 | 28 | public void setFullPackage(String fullPackage) { 29 | this.fullPackage = fullPackage; 30 | } 31 | 32 | public String getClassName() { 33 | return className; 34 | } 35 | 36 | public void setClassName(String className) { 37 | this.className = className; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return "JavaClassDefinition{" + 43 | "fullPackage='" + fullPackage + '\'' + 44 | ", className='" + className + '\'' + 45 | '}'; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/dto/JavaColumnInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.dto; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.database.entity.ColumnInfo; 4 | 5 | /** 6 | * java字段实体
7 | * time: 2018/7/29 16:06 8 | * 9 | * @author zhuo
10 | * @version 1.0 11 | */ 12 | public class JavaColumnInfo extends ColumnInfo { 13 | /** 转为驼峰命名后的字段名 */ 14 | private String javaColumnName; 15 | /** java字段类型 */ 16 | private String javaDataType; 17 | /** java字段类型全称 */ 18 | private String javaDataTypeFullPath; 19 | 20 | public JavaColumnInfo() { 21 | } 22 | 23 | public String getJavaColumnName() { 24 | return javaColumnName; 25 | } 26 | 27 | public void setJavaColumnName(String javaColumnName) { 28 | this.javaColumnName = javaColumnName; 29 | } 30 | 31 | public String getJavaDataType() { 32 | return javaDataType; 33 | } 34 | 35 | public void setJavaDataType(String javaDataType) { 36 | this.javaDataType = javaDataType; 37 | } 38 | 39 | public String getJavaDataTypeFullPath() { 40 | return javaDataTypeFullPath; 41 | } 42 | 43 | public void setJavaDataTypeFullPath(String javaDataTypeFullPath) { 44 | this.javaDataTypeFullPath = javaDataTypeFullPath; 45 | } 46 | 47 | @Override 48 | public String toString() { 49 | return "JavaColumnInfo{" + 50 | "javaColumnName='" + javaColumnName + '\'' + 51 | ", javaDataType='" + javaDataType + '\'' + 52 | ", javaDataTypeFullPath='" + javaDataTypeFullPath + '\'' + 53 | '}'; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/dto/MethodDescription.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.dto; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * 方法描述
8 | * time: 2019/5/21 9 | * @author zhuo
10 | * @since 1.4.0 11 | */ 12 | public class MethodDescription { 13 | /** 是否生成方法 */ 14 | private boolean enabled; 15 | /** 方法名 */ 16 | private String methodName; 17 | /** 方法注释 */ 18 | private String comment; 19 | /** 方法参数 */ 20 | private List params = new ArrayList<>(); 21 | 22 | public boolean isEnabled() { 23 | return enabled; 24 | } 25 | 26 | public void setEnabled(boolean enabled) { 27 | this.enabled = enabled; 28 | } 29 | 30 | public String getMethodName() { 31 | return methodName; 32 | } 33 | 34 | public void setMethodName(String methodName) { 35 | this.methodName = methodName; 36 | } 37 | 38 | public String getComment() { 39 | return comment; 40 | } 41 | 42 | public void setComment(String comment) { 43 | this.comment = comment; 44 | } 45 | 46 | public List getParams() { 47 | return params; 48 | } 49 | 50 | public void addParams(ParamDescription param) { 51 | if (param == null){ 52 | return; 53 | } 54 | this.params.add(param); 55 | } 56 | 57 | /** 58 | * 方法参数描述 59 | */ 60 | public class ParamDescription { 61 | /** 注释 */ 62 | private String comment; 63 | 64 | public ParamDescription(String comment) { 65 | this.comment = comment; 66 | } 67 | 68 | public String getComment() { 69 | return comment; 70 | } 71 | 72 | public void setComment(String comment) { 73 | this.comment = comment; 74 | } 75 | 76 | @Override 77 | public String toString() { 78 | return "ParamDescription{" + 79 | "comment='" + comment + '\'' + 80 | '}'; 81 | } 82 | } 83 | 84 | @Override 85 | public String toString() { 86 | return "MethodDescription{" + 87 | "enabled=" + enabled + 88 | ", methodName='" + methodName + '\'' + 89 | ", comment='" + comment + '\'' + 90 | ", params=" + params + 91 | '}'; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/dto/MybatisXmlDefinition.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.dto; 2 | 3 | import com.github.zhuyizhuo.generator.utils.TypeConversion; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | /** 9 | * mybatis 文件定义
10 | * 11 | * @author zhuo
12 | * @since 1.3.2 13 | */ 14 | public class MybatisXmlDefinition { 15 | /** 命名空间 */ 16 | private String nameSpace; 17 | /** 结果集 */ 18 | private ResultMapDefinition resultMap; 19 | /** xml 参数类型 -> method 关联? */ 20 | private String parameterType; 21 | /** 列信息定义 */ 22 | private List columns; 23 | 24 | public MybatisXmlDefinition() { 25 | resultMap = new ResultMapDefinition(); 26 | columns = new ArrayList<>(); 27 | } 28 | 29 | public String getParameterType() { 30 | return parameterType; 31 | } 32 | 33 | public void setParameterType(String parameterType) { 34 | this.parameterType = parameterType; 35 | } 36 | 37 | public ResultMapDefinition getResultMap() { 38 | return resultMap; 39 | } 40 | 41 | public String getNameSpace() { 42 | return nameSpace; 43 | } 44 | 45 | public void setNameSpace(String nameSpace) { 46 | this.nameSpace = nameSpace; 47 | } 48 | 49 | public List getColumns() { 50 | return columns; 51 | } 52 | 53 | public void addColumn(JavaColumnInfo columnInfo) { 54 | MybatisColumnDefinition mybatisColumnDefinition = new MybatisColumnDefinition(columnInfo); 55 | this.columns.add(mybatisColumnDefinition); 56 | } 57 | 58 | /** 59 | * 列定义 60 | */ 61 | public class MybatisColumnDefinition{ 62 | /** test 表达式 如果是 string 类型会判断是否空串 用于查询条件判断 */ 63 | private String testNotBlankExpression; 64 | /** test 表达式 用于插入条件判断 */ 65 | private String testNotNullExpression; 66 | /** 列名称 */ 67 | private String columnName; 68 | /** java 字段名 */ 69 | private String javaColumnName; 70 | /** java 字段类型 */ 71 | private String javaDataType; 72 | /** mybatis xml 中 JDBC 类型 */ 73 | private String jdbcType; 74 | /** mybatis xml中 parameterType */ 75 | private String parameterType; 76 | /** 是否主键 */ 77 | private boolean primaryKey; 78 | 79 | public MybatisColumnDefinition(JavaColumnInfo javaColumnInfo) { 80 | if (javaColumnInfo == null){ 81 | throw new IllegalArgumentException("Init MybatisColumnDefinition error ! javaColumnInfo is null !"); 82 | } 83 | this.javaColumnName = javaColumnInfo.getJavaColumnName(); 84 | this.javaDataType = javaColumnInfo.getJavaDataType(); 85 | this.columnName = javaColumnInfo.getColumnName(); 86 | this.primaryKey = javaColumnInfo.isPrimaryKey(); 87 | this.jdbcType = TypeConversion.type2JdbcType(javaColumnInfo.getDataType()); 88 | this.parameterType = TypeConversion.getMybatisParameterTypeByJavaDataType(javaColumnInfo.getJavaDataType()); 89 | this.testNotNullExpression = javaColumnName + " != null"; 90 | this.testNotBlankExpression = this.testNotNullExpression; 91 | if ("STRING".equalsIgnoreCase(javaDataType)){ 92 | this.testNotBlankExpression += " and " +javaColumnName+ " != '' "; 93 | } 94 | } 95 | 96 | public String getTestNotBlankExpression() { 97 | return testNotBlankExpression; 98 | } 99 | 100 | public String getTestNotNullExpression() { 101 | return testNotNullExpression; 102 | } 103 | 104 | public String getJdbcType() { 105 | return jdbcType; 106 | } 107 | 108 | public String getParameterType() { 109 | return parameterType; 110 | } 111 | 112 | public String getColumnName() { 113 | return columnName; 114 | } 115 | 116 | public String getJavaColumnName() { 117 | return javaColumnName; 118 | } 119 | 120 | public String getJavaDataType() { 121 | return javaDataType; 122 | } 123 | 124 | public boolean isPrimaryKey() { 125 | return primaryKey; 126 | } 127 | 128 | @Override 129 | public String toString() { 130 | return "MybatisColumnDefinition{" + 131 | "testNotBlankExpression='" + testNotBlankExpression + '\'' + 132 | ", testNotNullExpression='" + testNotNullExpression + '\'' + 133 | ", columnName='" + columnName + '\'' + 134 | ", javaColumnName='" + javaColumnName + '\'' + 135 | ", javaDataType='" + javaDataType + '\'' + 136 | ", jdbcType='" + jdbcType + '\'' + 137 | ", parameterType='" + parameterType + '\'' + 138 | ", primaryKey=" + primaryKey + 139 | '}'; 140 | } 141 | } 142 | 143 | /** 144 | * ResultMap 定义 145 | */ 146 | public class ResultMapDefinition { 147 | /** xml resultMap id */ 148 | private String id; 149 | /** 类型 */ 150 | private String type; 151 | 152 | public String getId() { 153 | return id; 154 | } 155 | 156 | public void setId(String id) { 157 | this.id = id; 158 | } 159 | 160 | public String getType() { 161 | return type; 162 | } 163 | 164 | public void setType(String type) { 165 | this.type = type; 166 | } 167 | 168 | @Override 169 | public String toString() { 170 | return "ResultMapDefinition{" + 171 | "id='" + id + '\'' + 172 | ", type='" + type + '\'' + 173 | '}'; 174 | } 175 | } 176 | 177 | public void setResultMapId(String id){ 178 | this.resultMap.setId(id); 179 | } 180 | 181 | public void setResultMapType(String type){ 182 | this.resultMap.setType(type); 183 | } 184 | 185 | @Override 186 | public String toString() { 187 | return "MybatisXmlDefinition{" + 188 | "nameSpace='" + nameSpace + '\'' + 189 | ", resultMap=" + resultMap + 190 | ", parameterType='" + parameterType + '\'' + 191 | ", columns=" + columns + 192 | '}'; 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/DefaultGenerator.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator; 2 | 3 | import com.github.zhuyizhuo.generator.enums.ErrorTypeEnums; 4 | import com.github.zhuyizhuo.generator.enums.FileTypeEnums; 5 | import com.github.zhuyizhuo.generator.enums.ModuleTypeEnums; 6 | import com.github.zhuyizhuo.generator.mybatis.convention.FileOutPathInfo; 7 | import com.github.zhuyizhuo.generator.mybatis.database.factory.DbServiceFactory; 8 | import com.github.zhuyizhuo.generator.mybatis.database.service.DbService; 9 | import com.github.zhuyizhuo.generator.mybatis.dto.MethodDescription; 10 | import com.github.zhuyizhuo.generator.mybatis.generator.extension.CustomizeModuleInfo; 11 | import com.github.zhuyizhuo.generator.mybatis.generator.extension.JavaModuleInfo; 12 | import com.github.zhuyizhuo.generator.mybatis.generator.service.GenerateService; 13 | import com.github.zhuyizhuo.generator.mybatis.generator.service.template.TemplateGenerateService; 14 | import com.github.zhuyizhuo.generator.mybatis.generator.support.ContextHolder; 15 | import com.github.zhuyizhuo.generator.mybatis.generator.support.MethodInfo; 16 | import com.github.zhuyizhuo.generator.mybatis.generator.support.ModuleInfo; 17 | import com.github.zhuyizhuo.generator.mybatis.vo.GenerateInfo; 18 | import com.github.zhuyizhuo.generator.mybatis.vo.GenerateMetaData; 19 | import com.github.zhuyizhuo.generator.mybatis.vo.ModulePathInfo; 20 | import com.github.zhuyizhuo.generator.mybatis.vo.TableInfo; 21 | import com.github.zhuyizhuo.generator.utils.LogUtils; 22 | 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | /** 27 | * 代码生成器 28 | * 29 | * @author zhuo 30 | * @since 1.0 31 | */ 32 | public class DefaultGenerator implements Generator{ 33 | /** 输出路径信息 */ 34 | private FileOutPathInfo fileOutPathInfo; 35 | /** 方法信息 */ 36 | private MethodInfo methodInfo; 37 | /** 代码生成器接口 */ 38 | private GenerateService generateService; 39 | 40 | DefaultGenerator(FileOutPathInfo fileOutPathInfo, MethodInfo methodInfo, GenerateService generateService) { 41 | this.fileOutPathInfo = fileOutPathInfo; 42 | this.methodInfo = methodInfo; 43 | this.generateService = generateService; 44 | } 45 | 46 | /** 47 | * 替换系统默认模板 48 | * @param moduleType 模块类型 49 | * @param templatePath 对应的模板路径 50 | * @since 1.5.0 51 | */ 52 | void replaceDefaultTemplate(ModuleTypeEnums moduleType, String templatePath){ 53 | if (generateService instanceof TemplateGenerateService) { 54 | TemplateGenerateService service = (TemplateGenerateService) this.generateService; 55 | service.addTemplate(moduleType.name(), templatePath); 56 | } 57 | } 58 | 59 | /** 60 | * 新增自定义 java 模块 61 | * @param javaModuleInfo java 模块信息 62 | */ 63 | void addJavaTemplate(JavaModuleInfo javaModuleInfo){ 64 | if (generateService instanceof TemplateGenerateService) { 65 | TemplateGenerateService service = (TemplateGenerateService) this.generateService; 66 | service.addTemplate(javaModuleInfo.getModuleType(), javaModuleInfo.getTemplatePath()); 67 | } 68 | this.fileOutPathInfo.addJavaTemplate(javaModuleInfo); 69 | } 70 | 71 | /** 72 | * 新增自定义模块 73 | * @param customizeModuleInfo 自定义模块信息 74 | */ 75 | void addCustomizeModuleInfo(CustomizeModuleInfo customizeModuleInfo){ 76 | if (generateService instanceof TemplateGenerateService) { 77 | TemplateGenerateService service = (TemplateGenerateService) this.generateService; 78 | service.addTemplate(customizeModuleInfo.getModuleType(), customizeModuleInfo.getTemplatePath()); 79 | } 80 | this.fileOutPathInfo.addCustomizeModule(customizeModuleInfo); 81 | } 82 | 83 | /** 84 | * 生成文件 85 | */ 86 | @Override 87 | public void generate(){ 88 | List tableColumns; 89 | try { 90 | DbService dbService = DbServiceFactory.getDbService(); 91 | tableColumns = dbService.getTableColumns(); 92 | } catch (Exception e){ 93 | LogUtils.error(e.getMessage()); 94 | LogUtils.printException(e); 95 | Throwable cause = e.getCause(); 96 | if (cause == null) { 97 | return; 98 | } 99 | String error = cause.toString(); 100 | if (error.contains(ErrorTypeEnums.CHECK_DEPENDENCE.getErrorMsg())) { 101 | LogUtils.error(ErrorTypeEnums.CHECK_DEPENDENCE.getMessage()); 102 | } else if(error.contains(ErrorTypeEnums.CHECK_DATABASE_CONFIG.getErrorMsg())){ 103 | LogUtils.error(ErrorTypeEnums.CHECK_DATABASE_CONFIG.getMessage()); 104 | } else { 105 | LogUtils.error(ErrorTypeEnums.ERROR_DATABASE_CONFIG.getMessage()); 106 | } 107 | return; 108 | } 109 | try { 110 | doGenerate(tableColumns); 111 | } catch (UnsupportedOperationException ue){ 112 | LogUtils.error("生成数据异常!UnsupportedOperationException:" + ue.getMessage()); 113 | LogUtils.printException(ue); 114 | } catch (Exception e){ 115 | LogUtils.error("生成数据异常!Exception:" + e.getMessage()); 116 | LogUtils.printException(e); 117 | } 118 | } 119 | 120 | private void doGenerate(List dbTableInfoList) { 121 | if (dbTableInfoList == null || dbTableInfoList.size() == 0){ 122 | LogUtils.info("不存在需生成的数据."); 123 | return; 124 | } 125 | 126 | GenerateMetaData generateMetaData = new GenerateMetaData(); 127 | ModulePathInfo modulePathInfo = null; 128 | GenerateInfo generateInfo; 129 | // 循环多表数据 130 | for (int i = 0; i < dbTableInfoList.size(); i++) { 131 | TableInfo tableInfo = dbTableInfoList.get(i); 132 | String tableName = tableInfo.getTableName(); 133 | this.fileOutPathInfo.initFileNamesAndOutPutFullPath(tableName, tableInfo.getTableNameCamelCase()); 134 | 135 | Map methodDescriptionMap = this.methodInfo.initMethodName(tableInfo.getTableName()); 136 | // 初始化 方法名 137 | generateInfo = new GenerateInfo(ContextHolder.getBean("classCommentInfo"), 138 | this.fileOutPathInfo.getJavaClassDefinitionMap(), 139 | methodDescriptionMap, tableInfo); 140 | 141 | List allModule = this.fileOutPathInfo.getAllModule(); 142 | for (int j = 0; j < allModule.size(); j++) { 143 | ModuleInfo info = allModule.get(j); 144 | modulePathInfo = new ModulePathInfo(info.getModuleType(), info.getOutPutFullPath()); 145 | if (FileTypeEnums.XML.equals(info.getFileType())){ 146 | generateInfo.initXmlInfo(); 147 | } 148 | generateMetaData.addModulePathInfo(tableName, modulePathInfo); 149 | generateMetaData.addGenerateInfo(tableName, generateInfo); 150 | } 151 | } 152 | generateService.generate(generateMetaData); 153 | } 154 | 155 | } 156 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/EmptyGenerator.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator; 2 | 3 | /** 4 | * 空生成器实例 当配置有误时返回 5 | * 6 | * @author zhuo 7 | * @since 1.5.0 8 | */ 9 | public class EmptyGenerator implements Generator { 10 | @Override 11 | public void generate() { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/Generator.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator; 2 | 3 | /** 4 | * 代码生成器接口 5 | * 6 | * @since 1.5.0 7 | */ 8 | public interface Generator { 9 | 10 | /** 11 | * 代码生成 12 | */ 13 | void generate(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/extension/CustomizeModuleInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.extension; 2 | 3 | import com.github.zhuyizhuo.generator.utils.CheckUtils; 4 | 5 | /** 6 | * 自定义模块
7 | * time: 2019-5-29 8 | * 9 | * @author zhuo
10 | * @since 1.4.0 11 | */ 12 | public class CustomizeModuleInfo { 13 | /** 模块 例如 controller service 等 */ 14 | private String moduleType; 15 | /** 模板路径 使用模板生成时 需要传入模板路径 */ 16 | private String templatePath; 17 | /** 18 | * 文件输出路径模板 如果单表生成 也可直接写为真实文件输出全路径 19 | * 20 | * @See java.text.MessageFormat#format(java.lang.String, java.lang.Object...) 21 | * outPutFullPathFormatPattern 为 第一个参数 22 | * 文件名为第二个参数 23 | */ 24 | private String outPutFullPathFormatPattern; 25 | /** 26 | * 文件名格式化 例如 {0}Mapper 适用于批量及单表生成 27 | * 或直接指定文件名 例如 UserMapper 仅适用于单表生成 28 | * 29 | * @See java.text.MessageFormat#format(java.lang.String, java.lang.Object...) 30 | * fileNameFormatPattern 为第一个参数 31 | * 表名转驼峰命名 为第二个参数 32 | * 33 | * 也可使用 GeneratorBuilder.addModuleNameFormat(moduleType,moduleNameFormatService) 34 | * 自定义本 moduleType 对应的文件名格式化 service 35 | * 36 | * 自定义 service 之后,本配置自动失效 37 | */ 38 | private String fileNameFormatPattern; 39 | 40 | public CustomizeModuleInfo(String moduleType, String templatePath, String outPutFullPathFormatPattern, String fileNameFormatPattern) { 41 | CheckUtils.assertNotNull(moduleType,"moduleType must not null!"); 42 | CheckUtils.assertNotNull(templatePath,"templatePath must not null!"); 43 | CheckUtils.assertNotNull(outPutFullPathFormatPattern,"outPutFullPathFormatPattern must not null!"); 44 | CheckUtils.assertNotNull(fileNameFormatPattern,"fileNameFormatPattern must not null!"); 45 | 46 | this.moduleType = moduleType; 47 | this.templatePath = templatePath; 48 | this.outPutFullPathFormatPattern = outPutFullPathFormatPattern; 49 | this.fileNameFormatPattern = fileNameFormatPattern; 50 | } 51 | 52 | public String getModuleType() { 53 | return moduleType; 54 | } 55 | 56 | public String getTemplatePath() { 57 | return templatePath; 58 | } 59 | 60 | public String getOutPutFullPathFormatPattern() { 61 | return outPutFullPathFormatPattern; 62 | } 63 | 64 | public String getFileNameFormatPattern() { 65 | return fileNameFormatPattern; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/extension/FormatService.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.extension; 2 | 3 | /** 4 | * 名称格式化
5 | * time: 2018/8/16 19:29 6 | * 7 | * @author zhuo
8 | * @since 1.0 9 | * @version 1.4.0 10 | */ 11 | public interface FormatService { 12 | 13 | /** 14 | * name 格式化 15 | * @param tableName 数据库表名 16 | * @return 格式化后的名称 17 | */ 18 | String format(String tableName); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/extension/JavaModuleInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.extension; 2 | 3 | import com.github.zhuyizhuo.generator.annotation.NotNull; 4 | import com.github.zhuyizhuo.generator.utils.CheckUtils; 5 | 6 | /** 7 | * 扩展 java 模块信息
8 | * time: 2019/5/27 9 | * 10 | * @author zhuo
11 | * @since 1.4.0 12 | */ 13 | public class JavaModuleInfo { 14 | /** 模块 例如 controller service 等 */ 15 | private String moduleType; 16 | /** 模板路径 使用模板生成时 需要传入模板路径 */ 17 | private String templatePath; 18 | /** 类的包路径 例如 com.baidu **/ 19 | private String classPackage; 20 | /** 输出路径 */ 21 | private String outputPath; 22 | /** 23 | * 文件名格式化 例如 {0}Mapper 适用于批量及单表生成 24 | * 或直接指定文件名 例如 UserMapper 仅适用于单表生成 25 | */ 26 | private String classNameFormat; 27 | 28 | public JavaModuleInfo(@NotNull String moduleType, @NotNull String templatePath, 29 | @NotNull String classPackage, @NotNull String outputPath, @NotNull String classNameFormat) { 30 | CheckUtils.assertNotNull(moduleType,"moduleType must not null!"); 31 | CheckUtils.assertNotNull(templatePath,"templatePath must not null!"); 32 | CheckUtils.assertNotNull(classPackage,"classPackage must not null!"); 33 | CheckUtils.assertNotNull(outputPath,"outputPath must not null!"); 34 | CheckUtils.assertNotNull(classNameFormat,"classNameFormat must not null!"); 35 | 36 | this.moduleType = moduleType; 37 | this.templatePath = templatePath; 38 | this.classPackage = classPackage; 39 | this.outputPath = outputPath; 40 | this.classNameFormat = classNameFormat; 41 | } 42 | 43 | public String getModuleType() { 44 | return moduleType; 45 | } 46 | 47 | public String getTemplatePath() { 48 | return templatePath; 49 | } 50 | 51 | public String getClassPackage() { 52 | return classPackage; 53 | } 54 | 55 | public String getClassNameFormat() { 56 | return classNameFormat; 57 | } 58 | 59 | public String getOutputPath() { 60 | return outputPath; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/extension/LogService.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.extension; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.vo.GenerateInfo; 4 | 5 | /** 6 | * 日志输出, 打印生成模板的元数据
7 | * time: 2019/6/6 8 | * 9 | * @author zhuo
10 | */ 11 | public interface LogService { 12 | 13 | /** 14 | * 输出生成信息 15 | * @param generateInfo 生成器处理后的生成数据使用的元数据 16 | */ 17 | void logGenerateInfo(GenerateInfo generateInfo); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/factory/GenerateServiceFactory.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.factory; 2 | 3 | import com.github.zhuyizhuo.generator.constants.ConfigConstants; 4 | import com.github.zhuyizhuo.generator.enums.DbTypeEnums; 5 | import com.github.zhuyizhuo.generator.enums.TemplateTypeEnums; 6 | import com.github.zhuyizhuo.generator.exception.GeneratorException; 7 | import com.github.zhuyizhuo.generator.mybatis.generator.service.GenerateService; 8 | import com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.impl.MybatisPlusGenerateImpl; 9 | import com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.impl.MysqlGenerateImpl; 10 | import com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.impl.OracleGenerateImpl; 11 | import com.github.zhuyizhuo.generator.mybatis.generator.support.ContextHolder; 12 | import com.github.zhuyizhuo.generator.utils.LogUtils; 13 | 14 | import java.util.Map; 15 | import java.util.concurrent.ConcurrentHashMap; 16 | 17 | /** 18 | * 生成器工厂
19 | * time: 2019/5/28 20 | * 21 | * @author zhuo
22 | * @since 1.4.0 23 | */ 24 | public class GenerateServiceFactory { 25 | 26 | private static Map serviceMap = new ConcurrentHashMap<>(); 27 | 28 | static{ 29 | serviceMap.put(TemplateTypeEnums.MYSQL.toString(), new MysqlGenerateImpl()); 30 | serviceMap.put(TemplateTypeEnums.ORACLE.toString(), new OracleGenerateImpl()); 31 | serviceMap.put(TemplateTypeEnums.MYBATIS_PLUS.toString(), new MybatisPlusGenerateImpl()); 32 | } 33 | 34 | public static GenerateService getGenerateService() throws GeneratorException { 35 | String dbType = ContextHolder.getConfig(ConfigConstants.DB_TYPE).toUpperCase(); 36 | GenerateService generateService = serviceMap.get(dbType); 37 | if (generateService == null){ 38 | String errorMsg = ConfigConstants.DB_TYPE + "配置类型不支持,所支持类型请参照 "+ DbTypeEnums.class.getName(); 39 | LogUtils.error(errorMsg); 40 | throw new GeneratorException(errorMsg); 41 | } 42 | return generateService; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/service/GenerateService.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.service; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.vo.GenerateMetaData; 4 | 5 | /** 6 | * 生成器 service
7 | * 8 | * @author zhuo
9 | * @since 1.4.0 10 | */ 11 | public interface GenerateService { 12 | 13 | /** 14 | * 文件生成 15 | * @param generateMetaData 生成所需元数据 16 | */ 17 | void generate(GenerateMetaData generateMetaData); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/service/template/TemplateGenerateService.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.service.template; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.generator.service.GenerateService; 4 | 5 | /** 6 | * 模板生成 service
7 | * 8 | * @author zhuo
9 | * @since 1.4.0 10 | */ 11 | public interface TemplateGenerateService extends GenerateService { 12 | 13 | /** 14 | * 增加模板 15 | * @param moduleType 模块类型 16 | * @param templatePath 模板路径 17 | */ 18 | void addTemplate(String moduleType,String templatePath); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/service/template/freemarker/FreemarkerGenerateService.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker; 2 | 3 | import com.github.zhuyizhuo.generator.enums.TemplateTypeEnums; 4 | import com.github.zhuyizhuo.generator.enums.ModuleTypeEnums; 5 | import com.github.zhuyizhuo.generator.mybatis.generator.service.template.TemplateGenerateService; 6 | import com.github.zhuyizhuo.generator.mybatis.vo.GenerateInfo; 7 | import com.github.zhuyizhuo.generator.mybatis.vo.GenerateMetaData; 8 | import com.github.zhuyizhuo.generator.mybatis.vo.ModulePathInfo; 9 | import com.github.zhuyizhuo.generator.mybatis.vo.TableInfo; 10 | import com.github.zhuyizhuo.generator.utils.Freemarker; 11 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 12 | import com.github.zhuyizhuo.generator.utils.LogUtils; 13 | 14 | import java.util.List; 15 | import java.util.Map; 16 | import java.util.concurrent.ConcurrentHashMap; 17 | 18 | /** 19 | * freemarker 模板生成 20 | */ 21 | public abstract class FreemarkerGenerateService implements TemplateGenerateService { 22 | /** 23 | * TemplateType_moduleType_hasPrivateKey -> templatePath 24 | */ 25 | private Map templatePathMap = new ConcurrentHashMap<>(); 26 | 27 | protected abstract TemplateTypeEnums getTemplateType(); 28 | 29 | protected void addTemplatePath(ModuleTypeEnums moduleType, Boolean hasPrivateKey, String templatePath){ 30 | if (hasPrivateKey == null){ 31 | addTemplate(moduleType.name(), templatePath); 32 | } else { 33 | this.templatePathMap.put(getTemplateType() + "_" + moduleType+ "_" + hasPrivateKey, templatePath); 34 | } 35 | } 36 | 37 | protected void addTemplatePath(ModuleTypeEnums moduleType, String templatePath) { 38 | addTemplate(moduleType.name(), templatePath); 39 | } 40 | 41 | @Override 42 | public void addTemplate(String moduleType, String templatePath) { 43 | this.templatePathMap.put(getTemplateType() + "_" + moduleType + "_true", templatePath); 44 | this.templatePathMap.put(getTemplateType() + "_" + moduleType + "_false", templatePath); 45 | } 46 | 47 | /** 48 | * 获取模板路径 49 | * @param moduleType 模块类型 50 | * @param hasPrivateKey 是否有主键 51 | * @return 模板路径 52 | */ 53 | protected String getTemplatePath(String moduleType, boolean hasPrivateKey) { 54 | return this.templatePathMap.get(getTemplateType() + "_" + moduleType + "_" + hasPrivateKey); 55 | } 56 | 57 | @Override 58 | public void generate(GenerateMetaData generateMetaData) { 59 | try { 60 | Map> tableInfosMap = generateMetaData.getModulePathInfoMap(); 61 | for (Map.Entry> entry : tableInfosMap.entrySet()) { 62 | List value = entry.getValue(); 63 | GenerateInfo generateInfo = generateMetaData.getGenerateInfoByTableName(entry.getKey()); 64 | TableInfo tableInfo = generateInfo.getTableInfo(); 65 | LogUtils.info(">>>>>>>>>>>>>>>>> generate [" + tableInfo.getTableName() + "] start <<<<<<<<<<<<<<<"); 66 | LogUtils.info(tableInfo.getTableName() + " 表共 " + tableInfo.getColumnLists().size() + " 列"); 67 | LogUtils.logGenerateInfo(generateInfo); 68 | boolean hasPrimaryKey = tableInfo.isHasPrimaryKey(); 69 | for (int i = 0; i < value.size(); i++) { 70 | ModulePathInfo templateGenerateInfo = value.get(i); 71 | String templatePath = this.getTemplatePath(templateGenerateInfo.getModuleType(), hasPrimaryKey); 72 | if (GeneratorStringUtils.isNotBlank(templatePath)){ 73 | Freemarker.printFile(templatePath, 74 | templateGenerateInfo.getFileOutputPath(), generateInfo); 75 | LogUtils.info("文件输出路径:"+templateGenerateInfo.getFileOutputPath()); 76 | } 77 | } 78 | LogUtils.info(">>>>>>>>>>>>>>>>> generate [" + tableInfo.getTableName() + "] end <<<<<<<<<<<<<<<<<"); 79 | } 80 | }catch (Exception e){ 81 | LogUtils.error("FreemarkerGenerateService.generate error!"); 82 | LogUtils.printException(e); 83 | } 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/service/template/freemarker/impl/MybatisPlusGenerateImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.impl; 2 | 3 | import com.github.zhuyizhuo.generator.constants.TemplateConstants; 4 | import com.github.zhuyizhuo.generator.enums.ModuleTypeEnums; 5 | import com.github.zhuyizhuo.generator.enums.TemplateTypeEnums; 6 | import com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.FreemarkerGenerateService; 7 | 8 | /** 9 | * MybatisPlus 模板生成
10 | * create time: 2020-10-28 21:37:06 11 | * 12 | * @author zhuo
13 | * @since 1.5.0 14 | */ 15 | public class MybatisPlusGenerateImpl extends FreemarkerGenerateService { 16 | 17 | public MybatisPlusGenerateImpl() { 18 | addTemplatePath(ModuleTypeEnums.XML, TemplateConstants.XML_MYBATIS_PLUS); 19 | 20 | addTemplatePath(ModuleTypeEnums.MAPPER, TemplateConstants.MAPPER_MYBATIS_PLUS); 21 | 22 | addTemplatePath(ModuleTypeEnums.MODEL, TemplateConstants.MODEL_MYBATIS_PLUS); 23 | 24 | addTemplatePath(ModuleTypeEnums.SERVICE, TemplateConstants.SERVICE_MYBATIS_PLUS); 25 | 26 | addTemplatePath(ModuleTypeEnums.SERVICE_IMPL, TemplateConstants.SERVICE_IMPL_MYBATIS_PLUS); 27 | } 28 | 29 | @Override 30 | protected TemplateTypeEnums getTemplateType() { 31 | return TemplateTypeEnums.MYBATIS_PLUS; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/service/template/freemarker/impl/MysqlGenerateImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.impl; 2 | 3 | import com.github.zhuyizhuo.generator.constants.TemplateConstants; 4 | import com.github.zhuyizhuo.generator.enums.ModuleTypeEnums; 5 | import com.github.zhuyizhuo.generator.enums.TemplateTypeEnums; 6 | import com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.FreemarkerGenerateService; 7 | 8 | /** 9 | * mysql 模板生成
10 | * 11 | * @author zhuo
12 | * @since 1.4.0 13 | */ 14 | public class MysqlGenerateImpl extends FreemarkerGenerateService { 15 | 16 | public MysqlGenerateImpl() { 17 | addTemplatePath(ModuleTypeEnums.XML,true, TemplateConstants.XML_MYSQL_HAS_PRIMARY_KEY); 18 | addTemplatePath(ModuleTypeEnums.XML,false, TemplateConstants.XML_MYSQL_NO_PRIMARY_KEY); 19 | 20 | addTemplatePath(ModuleTypeEnums.MAPPER,true, TemplateConstants.MAPPER_MYSQL_HAS_PRIMARY_KEY); 21 | addTemplatePath(ModuleTypeEnums.MAPPER,false, TemplateConstants.MAPPER_MYSQL_NO_PRIMARY_KEY); 22 | 23 | addTemplatePath(ModuleTypeEnums.MODEL, TemplateConstants.MODEL); 24 | } 25 | 26 | @Override 27 | protected TemplateTypeEnums getTemplateType() { 28 | return TemplateTypeEnums.MYSQL; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/service/template/freemarker/impl/OracleGenerateImpl.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.impl; 2 | 3 | import com.github.zhuyizhuo.generator.constants.TemplateConstants; 4 | import com.github.zhuyizhuo.generator.enums.ModuleTypeEnums; 5 | import com.github.zhuyizhuo.generator.enums.TemplateTypeEnums; 6 | import com.github.zhuyizhuo.generator.mybatis.generator.service.template.freemarker.FreemarkerGenerateService; 7 | 8 | /** 9 | * oracle 模板生成
10 | * 11 | * @author zhuo
12 | * @since 1.4.0 13 | */ 14 | public class OracleGenerateImpl extends FreemarkerGenerateService { 15 | 16 | public OracleGenerateImpl() { 17 | addTemplatePath(ModuleTypeEnums.XML,true, TemplateConstants.XML_ORACLE_HAS_PRIMARY_KEY); 18 | addTemplatePath(ModuleTypeEnums.XML,false, TemplateConstants.XML_ORACLE_NO_PRIMARY_KEY); 19 | 20 | addTemplatePath(ModuleTypeEnums.MAPPER,true, TemplateConstants.MAPPER_ORACLE_HAS_PRIMARY_KEY); 21 | addTemplatePath(ModuleTypeEnums.MAPPER,false, TemplateConstants.MAPPER_ORACLE_NO_PRIMARY_KEY); 22 | 23 | addTemplatePath(ModuleTypeEnums.MODEL, TemplateConstants.MODEL); 24 | } 25 | 26 | @Override 27 | protected TemplateTypeEnums getTemplateType() { 28 | return TemplateTypeEnums.ORACLE; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/support/ContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.support; 2 | 3 | import com.github.zhuyizhuo.generator.annotation.CoventionClass; 4 | import com.github.zhuyizhuo.generator.annotation.Resource; 5 | import com.github.zhuyizhuo.generator.annotation.Value; 6 | import com.github.zhuyizhuo.generator.exception.GeneratorException; 7 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 8 | import com.github.zhuyizhuo.generator.utils.LogUtils; 9 | import org.apache.ibatis.parsing.GenericTokenParser; 10 | import org.apache.ibatis.parsing.TokenHandler; 11 | 12 | import java.io.BufferedReader; 13 | import java.io.IOException; 14 | import java.io.InputStream; 15 | import java.io.InputStreamReader; 16 | import java.lang.reflect.Field; 17 | import java.nio.charset.StandardCharsets; 18 | import java.util.ArrayList; 19 | import java.util.Arrays; 20 | import java.util.Enumeration; 21 | import java.util.List; 22 | import java.util.Map; 23 | import java.util.Properties; 24 | import java.util.concurrent.ConcurrentHashMap; 25 | 26 | /** 27 | * 配置扫描 自动装配
28 | *

 29 |  *     扫描在 generator.properties 中配置的装配类(全路径),
 30 |  *     如果类上存在 CoventionClass 注解,则会对类中 @Value 标注的属性注入配置文件的对应配置。
 31 |  * 
32 | * time: 2019/5/23 33 | * 34 | * @author zhuo
35 | * @since 1.4.0 36 | */ 37 | @Resource("generate-config.properties") 38 | public class ContextHolder { 39 | 40 | private final static String resourceFile = "generator.properties"; 41 | /** 系统默认配置信息 */ 42 | private static Properties contextConfig = new Properties(); 43 | /** 生成器配置对象 map */ 44 | private static Map beanMap = new ConcurrentHashMap<>(); 45 | /** 自定义配置信息 */ 46 | private Properties customerProperties; 47 | 48 | private List classNames = new ArrayList<>(); 49 | 50 | private ContextHolder() {} 51 | 52 | private ContextHolder(Properties customerProperties) { 53 | this.customerProperties = customerProperties; 54 | } 55 | 56 | /** 57 | * 获取上下文实例 58 | * @param properties 59 | */ 60 | public static ContextHolder newInstance(Properties properties) throws GeneratorException { 61 | ContextHolder contextHolder = new ContextHolder(properties); 62 | contextHolder.init(); 63 | return contextHolder; 64 | } 65 | 66 | private void init() throws GeneratorException { 67 | try { 68 | Class aClass = this.getClass(); 69 | //定位 70 | doLoadConfig(aClass.getAnnotation(Resource.class).value()); 71 | //注册 72 | doRegister(); 73 | //注入 74 | doAutowired(); 75 | } catch (GeneratorException ge) { 76 | throw ge; 77 | } catch (Exception e){ 78 | LogUtils.error("生成器初始化异常! Exception:" + e.getMessage()); 79 | LogUtils.printException(e); 80 | throw new GeneratorException("生成器初始化失败!"); 81 | } 82 | } 83 | 84 | private void doAutowired() throws GeneratorException { 85 | if (beanMap.isEmpty()){return;} 86 | 87 | GenericTokenParser parser = new GenericTokenParser("#{", "}", new TokenHandler() { 88 | @Override 89 | public String handleToken(String content) { 90 | return handleConfig(content); 91 | } 92 | }); 93 | 94 | initProperties(parser); 95 | 96 | for (Map.Entry entry : beanMap.entrySet()){ 97 | Field[] declaredFields = entry.getValue().getClass().getDeclaredFields(); 98 | for (Field field : declaredFields) { 99 | if (!field.isAnnotationPresent(Value.class)){ continue;} 100 | 101 | String configValue = field.getAnnotation(Value.class).value().trim(); 102 | if ("".equals(configValue)){ 103 | configValue = field.getType().getName(); 104 | } 105 | 106 | field.setAccessible(true); 107 | try { 108 | while (configValue.contains("#")){ 109 | configValue = parser.parse(configValue); 110 | } 111 | field.set(entry.getValue(), configValue); 112 | } catch (IllegalAccessException e) { 113 | LogUtils.error("解析配置信息异常,entry key:"+entry.getKey() + 114 | ",entry value:" + entry.getValue() + 115 | ",configValue:" + configValue + 116 | ",Exception:" + e.getMessage()); 117 | LogUtils.printException(e); 118 | throw new GeneratorException("解析配置信息异常,entry key:"+entry.getKey() + 119 | ",entry value:" + entry.getValue() + 120 | ",configValue:" + configValue + 121 | ",Exception:" + e.getMessage()); 122 | } 123 | } 124 | } 125 | 126 | } 127 | 128 | private void initProperties(GenericTokenParser parser) { 129 | loopProperties(contextConfig, parser); 130 | if (customerProperties != null){ 131 | loopProperties(customerProperties, parser); 132 | //用户配置将覆盖系统默认同名配置 133 | contextConfig.putAll(customerProperties); 134 | } 135 | LogUtils.debug("配置信息:" , contextConfig); 136 | } 137 | 138 | /** 139 | * 处理带有 #{} 的属性 140 | */ 141 | private void loopProperties(Properties proInfo, GenericTokenParser parser) { 142 | Enumeration enumeration = proInfo.propertyNames(); 143 | while (enumeration.hasMoreElements()){ 144 | String key = (String)enumeration.nextElement(); 145 | String property = proInfo.getProperty(key); 146 | if (property != null && property.length() > 1){ 147 | while (property.contains("#")){ 148 | property = parser.parse(property); 149 | } 150 | proInfo.setProperty(key, property); 151 | } 152 | } 153 | } 154 | 155 | /** 156 | *

157 | * 按顺序依次获取配置,如果都未获取到 则返回空字符串 158 | * 159 | *

160 |      * 优先级:
161 |      * 1. 先获取用户的 java 配置
162 |      * 2. 获取配置文件配置
163 |      * 3. 获取环境变量
164 |      * 4. 获取系统变量
165 |      * 

166 | * @param key 配置键 167 | * @return 按顺序依次获取配置,如果都未获取到 则返回空字符串 168 | */ 169 | private String handleConfig(String key) { 170 | String property; 171 | if (customerProperties != null) { 172 | property = customerProperties.getProperty(key); 173 | if (GeneratorStringUtils.isNotBlank(property)){ 174 | return property.trim(); 175 | } 176 | } 177 | property = contextConfig.getProperty(key); 178 | if (GeneratorStringUtils.isNotBlank(property)){ 179 | return property.trim(); 180 | } 181 | property = System.getenv(key); 182 | if (GeneratorStringUtils.isNotBlank(property)) { 183 | return property.trim(); 184 | } 185 | property = System.getProperty(key); 186 | return GeneratorStringUtils.isNotBlank(property) ? property.trim() : ""; 187 | } 188 | 189 | private void doRegister() throws GeneratorException { 190 | if (classNames.isEmpty()) {return;} 191 | try { 192 | for (int i = 0; i < classNames.size(); i++) { 193 | String className = classNames.get(i); 194 | 195 | Class clazz = Class.forName(className); 196 | if (clazz.isAnnotationPresent(CoventionClass.class)){ 197 | String beanName = GeneratorStringUtils.firstLower(clazz.getSimpleName()); 198 | beanMap.put(beanName, clazz.newInstance()); 199 | } 200 | } 201 | } catch (Exception e) { 202 | LogUtils.error("doRegister error!Exception:" + e.getMessage()); 203 | LogUtils.printException(e); 204 | throw new GeneratorException("doRegister error!Exception:" + e.getMessage()); 205 | } 206 | } 207 | 208 | private void doLoadConfig(String contextConfigLocation) throws GeneratorException { 209 | ClassLoader classLoader = this.getClass().getClassLoader(); 210 | InputStream resourceAsStream = classLoader.getResourceAsStream(contextConfigLocation); 211 | try { 212 | contextConfig.load(new BufferedReader(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8))); 213 | 214 | resourceAsStream = classLoader.getResourceAsStream(resourceFile); 215 | Properties contextConfig = new Properties(); 216 | contextConfig.load(resourceAsStream); 217 | String property = contextConfig.getProperty("generate.convention.sourceType"); 218 | String[] split = property.split(","); 219 | this.classNames = Arrays.asList(split); 220 | } catch (IOException e) { 221 | LogUtils.error("doLoadConfig error!Exception:" + e.getMessage()); 222 | LogUtils.printException(e); 223 | throw new GeneratorException("doLoadConfig error!Exception:" + e.getMessage()); 224 | } finally { 225 | if (resourceAsStream != null) { 226 | try { 227 | resourceAsStream.close(); 228 | } catch (IOException e) { 229 | LogUtils.printException(e); 230 | } 231 | } 232 | } 233 | } 234 | 235 | public static T getBean(String beanName){ 236 | return (T) beanMap.get(GeneratorStringUtils.firstLower(beanName)); 237 | } 238 | 239 | public static String getConfig(String key){ 240 | String property = contextConfig.getProperty(key); 241 | LogUtils.debug("获取配置信息 key:" + key + ",value:" + property); 242 | return property == null ? "" : property; 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/support/MethodInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.support; 2 | 3 | import com.github.zhuyizhuo.generator.constants.ConfigConstants; 4 | import com.github.zhuyizhuo.generator.enums.MethodEnums; 5 | import com.github.zhuyizhuo.generator.mybatis.dto.MethodDescription; 6 | import com.github.zhuyizhuo.generator.mybatis.generator.extension.FormatService; 7 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 8 | import com.github.zhuyizhuo.generator.utils.PropertiesUtils; 9 | 10 | import java.text.MessageFormat; 11 | import java.util.Map; 12 | import java.util.concurrent.ConcurrentHashMap; 13 | 14 | /** 15 | * 方法相关参数 16 | * @author zhuo 17 | * @version 1.0 18 | * time: 2018/7/29 15:40 19 | */ 20 | public class MethodInfo { 21 | 22 | /** 23 | * method -> methodNameFormatService 24 | */ 25 | private Map methodNameFormatServiceMap; 26 | /** 27 | * 格式化全部方法名 service 28 | */ 29 | private FormatService commonMethodNameFormatService; 30 | 31 | public MethodInfo() {} 32 | 33 | public MethodInfo(Map methodNameFormatServiceMap, FormatService commonMethodNameFormatService) { 34 | this.methodNameFormatServiceMap = methodNameFormatServiceMap; 35 | this.commonMethodNameFormatService = commonMethodNameFormatService; 36 | } 37 | 38 | public Map initMethodName(String tableName) { 39 | Map methodDescriptionMap = new ConcurrentHashMap<>(); 40 | MethodDescription methodDescription; 41 | MethodEnums[] methodEnums = MethodEnums.values(); 42 | for (MethodEnums method : methodEnums) { 43 | if (MethodEnums.ALL_METHOD.equals(method)) { 44 | continue; 45 | } 46 | methodDescription = new MethodDescription(); 47 | methodDescription.setEnabled(PropertiesUtils.getBooleanConfigDefaultTrue(method.getPropertiesEnabledKey())); 48 | methodDescription.setMethodName(formatMethodName(method, tableName)); 49 | methodDescription.setComment(ContextHolder.getConfig(method.getMethodCommentKey())); 50 | methodDescription.addParams(methodDescription.new ParamDescription(tableName + " 参数对象")); 51 | methodDescriptionMap.put(method.toString(), methodDescription); 52 | } 53 | return methodDescriptionMap; 54 | } 55 | 56 | private String formatMethodName(MethodEnums method, String tableName){ 57 | FormatService formatService = null; 58 | if (this.methodNameFormatServiceMap != null){ 59 | formatService = methodNameFormatServiceMap.get(method); 60 | } 61 | if (formatService != null){ 62 | return formatService.format(tableName); 63 | } 64 | String methodName = this.commonMethodNameFormatService != null ? 65 | commonMethodNameFormatService.format(tableName) : 66 | GeneratorStringUtils.changeTableName2CamelFirstUpper(tableName, ContextHolder.getConfig(ConfigConstants.TABLE_SEPARATOR)); 67 | return MessageFormat.format(ContextHolder.getConfig(method.getMethodFormatKey()), methodName); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/generator/support/ModuleInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.generator.support; 2 | 3 | import com.github.zhuyizhuo.generator.enums.FileTypeEnums; 4 | import com.github.zhuyizhuo.generator.mybatis.generator.extension.FormatService; 5 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 6 | import com.github.zhuyizhuo.generator.utils.PathUtils; 7 | 8 | import java.text.MessageFormat; 9 | 10 | /** 11 | * 模块信息
12 | * time: 2019/5/27 13 | * 14 | * @author zhuo
15 | * @since 1.4.0 16 | */ 17 | public class ModuleInfo { 18 | /** 模块类型 */ 19 | private String moduleType; 20 | /** 文件类型 */ 21 | private FileTypeEnums fileType; 22 | /** 文件包路径 仅 java 模块需设置包路径 */ 23 | private String fileFullPackage; 24 | /** 25 | * 文件名格式化 26 | * 例如 {0}Mapper 27 | * @See java.text.MessageFormat#format(java.lang.String, java.lang.Object...) 28 | * fileNameFormatPattern 为第一个参数 29 | * 表名转驼峰命名 为第二个参数 30 | * 31 | * 优先级低于 ModuleInfo#fileNameFormatServie 32 | * 如果设置了 fileNameFormatServie 则 该配置自动失效 33 | */ 34 | private String fileNameFormatPattern; 35 | /** 36 | * 文件输出路径模板 37 | * @See java.text.MessageFormat#format(java.lang.String, java.lang.Object...) 38 | * outPutFullPathFormatPattern 为 第一个参数 39 | * 文件名为第二个参数 40 | */ 41 | private String outPutFullPathFormatPattern; 42 | /** 43 | * 文件名格式化 service 44 | * 可使用 GeneratorBuilder.addModuleNameFormat(moduleType,moduleNameFormatService) 45 | * 自定义文件名格式化 Service 46 | */ 47 | private FormatService fileNameFormatServie; 48 | /** 49 | * 文件输出全路径 50 | * 将文件输出路径模板格式化后 设置 51 | */ 52 | private String outPutFullPath; 53 | 54 | public String getModuleType() { 55 | return moduleType; 56 | } 57 | 58 | public void setModuleType(String moduleType) { 59 | this.moduleType = moduleType; 60 | } 61 | 62 | public String getFileFullPackage() { 63 | return fileFullPackage; 64 | } 65 | 66 | public void setFileFullPackage(String fileFullPackage) { 67 | this.fileFullPackage = fileFullPackage; 68 | } 69 | 70 | public String getOutPutFullPathFormatPattern() { 71 | return outPutFullPathFormatPattern; 72 | } 73 | 74 | public void setOutPutFullPathFormatPattern(String outPutFullPathFormatPattern) { 75 | this.outPutFullPathFormatPattern = outPutFullPathFormatPattern; 76 | } 77 | 78 | public FormatService getFileNameFormatServie() { 79 | return fileNameFormatServie; 80 | } 81 | 82 | public void setFileNameFormatServie(FormatService fileNameFormatServie) { 83 | this.fileNameFormatServie = fileNameFormatServie; 84 | } 85 | 86 | public String getOutPutFullPath() { 87 | if (GeneratorStringUtils.isNotBlank(this.outPutFullPath)){ 88 | String collapsePath = new PathUtils('/').collapseFrom(this.outPutFullPath, '/'); 89 | return new PathUtils('\\').collapseFrom(collapsePath, '/'); 90 | } 91 | return outPutFullPath; 92 | } 93 | 94 | /** 95 | * 设置文件全路径 96 | * @param fileName 文件名 97 | */ 98 | public void setOutPutFullPathByFileName(String fileName) { 99 | this.outPutFullPath = MessageFormat.format(getOutPutFullPathFormatPattern(), fileName); 100 | } 101 | 102 | public FileTypeEnums getFileType() { 103 | return fileType; 104 | } 105 | 106 | public void setFileType(FileTypeEnums fileType) { 107 | this.fileType = fileType; 108 | } 109 | 110 | public String getFileNameFormatPattern() { 111 | return fileNameFormatPattern; 112 | } 113 | 114 | public void setFileNameFormatPattern(String fileNameFormatPattern) { 115 | this.fileNameFormatPattern = fileNameFormatPattern; 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/vo/GenerateInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.vo; 2 | 3 | import com.github.zhuyizhuo.generator.constants.ConfigConstants; 4 | import com.github.zhuyizhuo.generator.mybatis.convention.ClassCommentInfo; 5 | import com.github.zhuyizhuo.generator.mybatis.dto.JavaClassDefinition; 6 | import com.github.zhuyizhuo.generator.mybatis.dto.MethodDescription; 7 | import com.github.zhuyizhuo.generator.mybatis.dto.JavaColumnInfo; 8 | import com.github.zhuyizhuo.generator.enums.ModuleTypeEnums; 9 | import com.github.zhuyizhuo.generator.mybatis.dto.MybatisXmlDefinition; 10 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 11 | import com.github.zhuyizhuo.generator.utils.PropertiesUtils; 12 | 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | /** 17 | * 生成所需元信息 18 | * 19 | * @author zhuo 20 | * @version 1.0 21 | * time: 2018/7/29 17:44 22 | */ 23 | public class GenerateInfo { 24 | /** 类注释信息 */ 25 | private ClassCommentInfo classCommentInfo; 26 | /** 分层信息 */ 27 | private Map javaClassDefinition; 28 | /** 方法信息 */ 29 | private Map methodDescription; 30 | /** 表信息 */ 31 | private TableInfo tableInfo; 32 | /** mybatis xml 定义*/ 33 | private MybatisXmlDefinition mybatisXmlDefinition; 34 | 35 | public GenerateInfo() { } 36 | 37 | public GenerateInfo(ClassCommentInfo classCommentInfo, Map javaClassDefinition, Map methodDescription, TableInfo tableInfo) { 38 | this.classCommentInfo = classCommentInfo; 39 | this.javaClassDefinition = javaClassDefinition; 40 | this.methodDescription = methodDescription; 41 | this.tableInfo = tableInfo; 42 | } 43 | 44 | public ClassCommentInfo getClassCommentInfo() { 45 | return classCommentInfo; 46 | } 47 | 48 | public void setClassCommentInfo(ClassCommentInfo classCommentInfo) { 49 | this.classCommentInfo = classCommentInfo; 50 | } 51 | 52 | public TableInfo getTableInfo() { 53 | return tableInfo; 54 | } 55 | 56 | public MybatisXmlDefinition getMybatisXmlDefinition() { 57 | return mybatisXmlDefinition; 58 | } 59 | 60 | public void initXmlInfo() { 61 | mybatisXmlDefinition = new MybatisXmlDefinition(); 62 | 63 | boolean useTypeAliases = PropertiesUtils.getBooleanConfigDefaultFalse(ConfigConstants.PARAMETER_TYPE_USE_TYPE_ALIASES); 64 | JavaClassDefinition modelDefinition = javaClassDefinition.get(ModuleTypeEnums.MODEL.toString()); 65 | JavaClassDefinition mapperDefinition = javaClassDefinition.get(ModuleTypeEnums.MAPPER.toString()); 66 | 67 | String className = GeneratorStringUtils.firstLower(modelDefinition.getClassName()); 68 | mybatisXmlDefinition.setParameterType(useTypeAliases ? className 69 | : modelDefinition.getFullPackage()+"."+modelDefinition.getClassName()); 70 | mybatisXmlDefinition.setNameSpace(mapperDefinition.getFullPackage()+"." +mapperDefinition.getClassName()); 71 | mybatisXmlDefinition.setResultMapId(className+"ResultMap"); 72 | mybatisXmlDefinition.setResultMapType(mybatisXmlDefinition.getParameterType()); 73 | 74 | List columns = tableInfo.getColumnLists(); 75 | for (int i = 0; i < columns.size(); i++) { 76 | JavaColumnInfo javaColumnInfo = columns.get(i); 77 | mybatisXmlDefinition.addColumn(javaColumnInfo); 78 | } 79 | } 80 | 81 | public Map getMethodDescription() { 82 | return methodDescription; 83 | } 84 | 85 | public Map getJavaClassDefinition() { 86 | return javaClassDefinition; 87 | } 88 | 89 | @Override 90 | public String toString() { 91 | return "GenerateInfo{" + 92 | "classCommentInfo=" + classCommentInfo + 93 | ", javaClassDefinition=" + javaClassDefinition + 94 | ", methodDescription=" + methodDescription + 95 | ", tableInfo=" + tableInfo + 96 | ", mybatisXmlDefinition=" + mybatisXmlDefinition + 97 | '}'; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/vo/GenerateMetaData.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.vo; 2 | 3 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 4 | 5 | import java.util.*; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | /** 9 | * 生成文件所需元信息 10 | */ 11 | public class GenerateMetaData { 12 | /*** 13 | * 表名 -> 该表需生成的所有模块集合 14 | */ 15 | private Map> modulePathInfoMap = new LinkedHashMap<>(); 16 | /*** 17 | * 表名对应生成信息 18 | */ 19 | private Map tableGenerateInfoMap = new ConcurrentHashMap<>(); 20 | 21 | public Map> getModulePathInfoMap() { 22 | return modulePathInfoMap; 23 | } 24 | 25 | public void addModulePathInfo(String tableName, ModulePathInfo modulePathInfo) { 26 | if (GeneratorStringUtils.isBlank(tableName) || modulePathInfo == null){ 27 | return; 28 | } 29 | if (modulePathInfoMap.get(tableName) != null){ 30 | modulePathInfoMap.get(tableName).add(modulePathInfo); 31 | } else { 32 | List modules = new ArrayList<>(); 33 | modules.add(modulePathInfo); 34 | modulePathInfoMap.put(tableName, modules); 35 | } 36 | } 37 | 38 | public void addGenerateInfo(String tableName, GenerateInfo generateInfo){ 39 | if (GeneratorStringUtils.isBlank(tableName) || generateInfo == null){ 40 | return; 41 | } 42 | tableGenerateInfoMap.put(tableName, generateInfo); 43 | } 44 | 45 | /** 46 | * 根据表名 获取 生成所需信息 47 | * @param tableName 表名 48 | * @return 生成所需信息 49 | */ 50 | public GenerateInfo getGenerateInfoByTableName(String tableName){ 51 | return tableGenerateInfoMap.get(tableName); 52 | } 53 | 54 | public Map getTableGenerateInfoMap() { 55 | return tableGenerateInfoMap; 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/vo/ModulePathInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.vo; 2 | 3 | /** 4 | * 模块信息
5 | * time: 2019/5/23 6 | * 7 | * @author zhuo
8 | * @since 1.4.0 9 | */ 10 | public class ModulePathInfo { 11 | /** 模块类型 */ 12 | private String moduleType; 13 | /** 生成文件输出路径 */ 14 | private String fileOutputPath; 15 | 16 | public ModulePathInfo(String moduleType, String fileOutputPath) { 17 | this.moduleType = moduleType; 18 | this.fileOutputPath = fileOutputPath; 19 | } 20 | 21 | public String getModuleType() { 22 | return moduleType; 23 | } 24 | 25 | public void setModuleType(String moduleType) { 26 | this.moduleType = moduleType; 27 | } 28 | 29 | public String getFileOutputPath() { 30 | return fileOutputPath; 31 | } 32 | 33 | public void setFileOutputPath(String fileOutputPath) { 34 | this.fileOutputPath = fileOutputPath; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/mybatis/vo/TableInfo.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.mybatis.vo; 2 | 3 | import com.github.zhuyizhuo.generator.mybatis.database.entity.ColumnInfo; 4 | import com.github.zhuyizhuo.generator.mybatis.dto.JavaColumnInfo; 5 | import com.github.zhuyizhuo.generator.utils.GeneratorStringUtils; 6 | 7 | import java.util.ArrayList; 8 | import java.util.LinkedHashSet; 9 | import java.util.List; 10 | 11 | /** 12 | * 生成模板所用对象
13 | * time: 2018/8/3 19:56 14 | * 15 | * @author zhuo
16 | * @version 1.0 17 | */ 18 | public class TableInfo { 19 | /** 数据库名称 */ 20 | private String tableSchema; 21 | /** 表名 */ 22 | private String tableName; 23 | /** 表注释 */ 24 | private String tableComment; 25 | /** 表名转驼峰 首字母大写 */ 26 | private String tableNameCamelCase; 27 | /** 导入的类路径 */ 28 | private LinkedHashSet importPackages; 29 | /** 表所有字段 */ 30 | private List columnLists; 31 | /** 主键字段 */ 32 | private List primaryKeyColumns; 33 | /** 是否有主键 */ 34 | private boolean hasPrimaryKey; 35 | /** 是否单个主键 */ 36 | private boolean singlePrimaryKey; 37 | 38 | public TableInfo() { 39 | importPackages = new LinkedHashSet<>(); 40 | columnLists = new ArrayList<>(); 41 | primaryKeyColumns = new ArrayList<>(); 42 | hasPrimaryKey = false; 43 | singlePrimaryKey = false; 44 | } 45 | 46 | public String getTableSchema() { 47 | return tableSchema; 48 | } 49 | 50 | public void setTableSchema(String tableSchema) { 51 | this.tableSchema = tableSchema; 52 | } 53 | 54 | public String getTableName() { 55 | return tableName; 56 | } 57 | 58 | public void setTableName(String tableName) { 59 | this.tableName = tableName; 60 | } 61 | 62 | public String getTableComment() { 63 | return tableComment; 64 | } 65 | 66 | public void setTableComment(String tableComment) { 67 | this.tableComment = tableComment; 68 | } 69 | 70 | public List getColumnLists() { 71 | return columnLists; 72 | } 73 | 74 | public void addJavaColumnInfo(JavaColumnInfo javaColumnInfo) { 75 | this.columnLists.add(javaColumnInfo); 76 | } 77 | 78 | public String getTableNameCamelCase() { 79 | return tableNameCamelCase; 80 | } 81 | 82 | public void setTableNameCamelCase(String tableNameCamelCase) { 83 | this.tableNameCamelCase = tableNameCamelCase; 84 | } 85 | 86 | public LinkedHashSet getImportPackages() { 87 | return importPackages; 88 | } 89 | 90 | public void addImportPackage(String importPackage) { 91 | if (importPackage == null){ 92 | return; 93 | } 94 | this.importPackages.add(importPackage); 95 | } 96 | 97 | public void addPrimaryKeyColumn(List keyName) { 98 | if (keyName == null || keyName.size() == 0){ 99 | return; 100 | } 101 | for (int i = 0; i < keyName.size(); i++) { 102 | ColumnInfo columnInfo = keyName.get(i); 103 | String columnName = columnInfo.getColumnName(); 104 | if (GeneratorStringUtils.isNotBlank(columnName)){ 105 | for (int j = 0; j < columnLists.size(); j++) { 106 | JavaColumnInfo javaColumnInfo = columnLists.get(j); 107 | if (columnName.equalsIgnoreCase(javaColumnInfo.getColumnName())){ 108 | javaColumnInfo.setPrimaryKey(true); 109 | this.primaryKeyColumns.add(javaColumnInfo); 110 | break; 111 | } 112 | } 113 | } 114 | } 115 | 116 | this.hasPrimaryKey = true; 117 | this.singlePrimaryKey = primaryKeyColumns.size() == 1; 118 | } 119 | 120 | public List getPrimaryKeyColumns() { 121 | return primaryKeyColumns; 122 | } 123 | 124 | public boolean isHasPrimaryKey() { 125 | return hasPrimaryKey; 126 | } 127 | 128 | public void setHasPrimaryKey(boolean hasPrimaryKey) { 129 | this.hasPrimaryKey = hasPrimaryKey; 130 | } 131 | 132 | public boolean isSinglePrimaryKey() { 133 | return singlePrimaryKey; 134 | } 135 | 136 | public void setSinglePrimaryKey(boolean singlePrimaryKey) { 137 | this.singlePrimaryKey = singlePrimaryKey; 138 | } 139 | 140 | @Override 141 | public String toString() { 142 | return "TableInfo{" + 143 | " tableSchema='" + tableSchema + '\'' + 144 | ", tableName='" + tableName + '\'' + 145 | ", tableComment='" + tableComment + '\'' + 146 | ", tableNameCamelCase='" + tableNameCamelCase + '\'' + 147 | ", importPackages=" + importPackages + 148 | ", columnLists=" + columnLists + 149 | ", primaryKeyColumns=" + primaryKeyColumns + 150 | ", hasPrimaryKey=" + hasPrimaryKey + 151 | ", singlePrimaryKey=" + singlePrimaryKey + 152 | '}'; 153 | } 154 | } -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/utils/CheckUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.utils; 2 | 3 | import com.github.zhuyizhuo.generator.exception.GeneratorException; 4 | import com.github.zhuyizhuo.generator.constants.ConfigConstants; 5 | import com.github.zhuyizhuo.generator.enums.DbTypeEnums; 6 | 7 | import java.util.Properties; 8 | 9 | /** 10 | * 校验工具
11 | * time: 2018/8/20 13:01 12 | * 13 | * @author zhuo
14 | * @since 1.3.0 15 | */ 16 | public class CheckUtils { 17 | public static final String[] dbConfig = {ConfigConstants.DB_TYPE,ConfigConstants.URL,ConfigConstants.DRIVER, 18 | ConfigConstants.USERNAME,ConfigConstants.PASSWORD,ConfigConstants.TABLE_SCHEMA}; 19 | 20 | public static void assertNotNull(Object moduleType, String errorMsg) throws IllegalArgumentException { 21 | if (moduleType == null){ 22 | throw new IllegalArgumentException(errorMsg); 23 | } 24 | } 25 | 26 | public static void assertNotNull(String moduleType, String errorMsg) throws IllegalArgumentException { 27 | if(GeneratorStringUtils.isBlank(moduleType)){ 28 | throw new IllegalArgumentException(errorMsg); 29 | } 30 | } 31 | 32 | public static Properties checkDatabaseConfig(Properties properties) throws GeneratorException { 33 | Properties rtnProperties = new Properties(); 34 | StringBuffer errorMsg = new StringBuffer(); 35 | for (int i = 0; i < dbConfig.length; i++) { 36 | String needProperties = properties.getProperty(dbConfig[i]); 37 | if (GeneratorStringUtils.isBlank(needProperties)){ 38 | errorMsg.append("未配置 " + dbConfig[i] + " \n"); 39 | } else { 40 | rtnProperties.put(dbConfig[i], needProperties); 41 | } 42 | } 43 | try { 44 | DbTypeEnums.valueOf(properties.getProperty(ConfigConstants.DB_TYPE).toUpperCase()); 45 | } catch (Exception e){ 46 | DbTypeEnums[] values = DbTypeEnums.values(); 47 | errorMsg.append(ConfigConstants.DB_TYPE) 48 | .append(" 配置有误, 支持配置类型:"); 49 | for (int i = 0; i < values.length; i++) { 50 | errorMsg.append(values[i].name()).append(" "); 51 | } 52 | } 53 | if (errorMsg.length() > 0){ 54 | LogUtils.logProperties("数据库配置信息:", rtnProperties); 55 | throw new GeneratorException(errorMsg.toString()); 56 | } 57 | return rtnProperties; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/utils/Freemarker.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.utils; 2 | 3 | import freemarker.template.Configuration; 4 | import freemarker.template.Template; 5 | import freemarker.template.TemplateException; 6 | 7 | import java.io.BufferedWriter; 8 | import java.io.File; 9 | import java.io.FileOutputStream; 10 | import java.io.IOException; 11 | import java.io.OutputStreamWriter; 12 | import java.io.Writer; 13 | import java.util.Locale; 14 | 15 | /** 16 | * freemarker 工具类 17 | * 创建时间:2015年2月8日 18 | * @version 1.0 19 | */ 20 | public class Freemarker { 21 | 22 | /** 23 | * 输出对象到文件 24 | * @param ftlFullPath ftl模板路径 25 | * @param outPutPath 输出文件全路径 26 | * @param outPutObject 输出对象 27 | * @throws Exception 获取模板异常抛出 28 | */ 29 | public static void printFile(String ftlFullPath, String outPutPath, Object outPutObject) throws Exception{ 30 | printFile(GeneratorStringUtils.getFrontPath(ftlFullPath),GeneratorStringUtils.getFileName(ftlFullPath),outPutPath,outPutObject); 31 | } 32 | 33 | /** 34 | * 将root对象输出到文件 35 | * @param ftlPath ftl文件路径 36 | * @param ftlName ftl文件名 37 | * @param outPutPath 输出后的文件全部路径 38 | * @param outPutObject 输出对象 39 | * @throws Exception 获取模板异常抛出 40 | */ 41 | public static void printFile(String ftlPath, String ftlName, String outPutPath, Object outPutObject) throws Exception { 42 | try { 43 | File file = new File(outPutPath); 44 | //判断有没有父路径,就是判断文件整个路径是否存在 45 | if(file != null && file.getParentFile() != null && !file.getParentFile().exists()){ 46 | //不存在就全部创建 47 | file.getParentFile().mkdirs(); 48 | } 49 | Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); 50 | Template template = getTemplate(ftlPath, ftlName); 51 | //模版输出 52 | template.process(outPutObject, out); 53 | out.flush(); 54 | out.close(); 55 | } catch (TemplateException e) { 56 | LogUtils.printException(e); 57 | } catch (IOException e) { 58 | LogUtils.printException(e); 59 | } 60 | } 61 | 62 | /** 63 | * 通过文件名加载模版 64 | * @param ftlPath ftl文件路径 65 | * @param ftlName ftl文件名 66 | * @throws Exception 读取模板失败抛出异常 67 | * @return Template 模板 68 | */ 69 | public static Template getTemplate(String ftlPath, String ftlName) throws Exception{ 70 | try { 71 | //通过Freemaker的Configuration读取相应的ftl 72 | Configuration cfg = new Configuration(Configuration.VERSION_2_3_0); 73 | cfg.setEncoding(Locale.CHINA, "utf-8"); 74 | //设定去哪里读取相应的ftl模板文件 75 | cfg.setClassLoaderForTemplateLoading(Freemarker.class.getClassLoader(), ftlPath); 76 | //在模板文件目录中找到名称为name的文件 77 | return cfg.getTemplate(ftlName); 78 | } catch (IOException e) { 79 | LogUtils.printException(e); 80 | } 81 | return null; 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/utils/GeneratorStringUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.utils; 2 | 3 | /** 4 | * 字符串工具类
5 | * time: 2018/7/27 11:35 6 | * 7 | * @author zhuo
8 | * @version 1.0 9 | */ 10 | public class GeneratorStringUtils { 11 | 12 | /** 13 | * 获取传入文件全路径的路径信息 14 | * @param fileFullpath d:/e/a/1.txt 15 | * @return d:/e/a/ 16 | */ 17 | public static String getFrontPath(String fileFullpath){ 18 | if (isBlank(fileFullpath)){ 19 | return ""; 20 | } 21 | String fullPath = fileFullpath.replaceAll("\\\\","/"); 22 | return fullPath.substring(0,fullPath.lastIndexOf("/") + 1); 23 | } 24 | 25 | /** 26 | * 获取传入文件全路径的文件名称 27 | * @param fileFullpath d:/e/a/1.txt 28 | * @return 1.txt 29 | */ 30 | public static String getFileName(String fileFullpath){ 31 | if (isBlank(fileFullpath)){ 32 | return ""; 33 | } 34 | String fullPath = fileFullpath.replaceAll("\\\\","/"); 35 | return fullPath.substring(fullPath.lastIndexOf("/") + 1); 36 | } 37 | 38 | /** 39 | *

Checks if a CharSequence is whitespace, empty ("") or null.

40 | * 41 | *
 42 |      * GeneratorStringUtils.isBlank(null)      = true
 43 |      * GeneratorStringUtils.isBlank("")        = true
 44 |      * GeneratorStringUtils.isBlank(" ")       = true
 45 |      * GeneratorStringUtils.isBlank("bob")     = false
 46 |      * GeneratorStringUtils.isBlank("  bob  ") = false
 47 |      * 
48 | * 49 | * @param cs the CharSequence to check, may be null 50 | * @return {@code true} if the CharSequence is null, empty or whitespace 51 | */ 52 | public static boolean isBlank(final CharSequence cs) { 53 | int strLen; 54 | if (cs == null || (strLen = cs.length()) == 0) { 55 | return true; 56 | } 57 | for (int i = 0; i < strLen; i++) { 58 | if (Character.isWhitespace(cs.charAt(i)) == false) { 59 | return false; 60 | } 61 | } 62 | return true; 63 | } 64 | 65 | /** 66 | *

Checks if a CharSequence is not empty (""), not null and not whitespace only.

67 | * 68 | *
 69 |      * StringUtils.isNotBlank(null)      = false
 70 |      * StringUtils.isNotBlank("")        = false
 71 |      * StringUtils.isNotBlank(" ")       = false
 72 |      * StringUtils.isNotBlank("bob")     = true
 73 |      * StringUtils.isNotBlank("  bob  ") = true
 74 |      * 
75 | * 76 | * @param cs the CharSequence to check, may be null 77 | * @return {@code true} if the CharSequence is 78 | * not empty and not null and not whitespace 79 | */ 80 | public static boolean isNotBlank(final CharSequence cs) { 81 | return !isBlank(cs); 82 | } 83 | 84 | /** 85 | * 表名转java驼峰命名(首字母大写) 86 | * @param tableName e.g mybatis_user_info 87 | * @param tableRegex 表名的分隔符 例如 _ 88 | * @return MybatisUserInfo 89 | */ 90 | public static String changeTableName2CamelFirstUpper(String tableName, String tableRegex) { 91 | String[] split = tableName.split(tableRegex); 92 | StringBuffer s = new StringBuffer(); 93 | for (int i = 0; i < split.length; i++) { 94 | s.append(firstUpper(split[i])); 95 | } 96 | return s.toString(); 97 | } 98 | 99 | /** 100 | * 数据库字段名转java驼峰命名(驼峰处转大写,其他字母小写) 连接符colmRegex可指定 默认为_ 101 | * changeColmName2CamelFirstLower("mybatis_user_info","_") = "mybatisUserInfo" 102 | * changeColmName2CamelFirstLower("MYBATIS_USER_INFO","_") = "mybatisUserInfo" 103 | * @param columnName 列名 104 | * @param colmRegex 字段的分隔符 例如 _ 105 | * @return java驼峰命名 106 | */ 107 | public static String changeColmName2CamelFirstLower(String columnName, String colmRegex) { 108 | String[] split = columnName.split(colmRegex); 109 | StringBuffer s = new StringBuffer(); 110 | char[] charArray = split[0].toCharArray(); 111 | for (int i = 0; i < charArray.length; i++) { 112 | s.append(toL(charArray[i])); 113 | } 114 | for (int i = 1; i < split.length; i++) { 115 | s.append(firstUpper(split[i])); 116 | } 117 | return s.toString(); 118 | } 119 | 120 | /** 121 | * 首字母大写 其他字母小写 122 | * @param str 传入纯字母字符串 123 | * @return 首字母大写 其他字母小写 124 | */ 125 | public static String firstUpper(String str) { 126 | char[] cs = str.toCharArray(); 127 | cs[0] = toU(cs[0]); 128 | for (int i = 1; i < cs.length; i++) { 129 | cs[i] = toL(cs[i]); 130 | } 131 | return String.valueOf(cs); 132 | } 133 | 134 | /** 135 | * 首字母小写 136 | * @param str 传入纯字母字符串 137 | * @return 将首字母小写后返回 138 | */ 139 | public static String firstLower(String str) { 140 | char[] cs = str.toCharArray(); 141 | cs[0] = toL(cs[0]); 142 | return String.valueOf(cs); 143 | } 144 | 145 | /** 146 | * 字母转大写 147 | * @param c a-z 148 | * @return A-Z 149 | */ 150 | public static char toU(char c) { 151 | if (c >= 'a' && c <= 'z') { 152 | return (char)(c - 32); 153 | } 154 | return c; 155 | } 156 | 157 | /** 158 | * 字母转小写 159 | * @param c A-Z 160 | * @return a-z 161 | */ 162 | public static char toL(char c) { 163 | if (c >= 'A' && c <= 'Z') { 164 | return (char)(c + 32); 165 | } 166 | return c; 167 | } 168 | 169 | } 170 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/utils/LogUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.utils; 2 | 3 | import com.github.zhuyizhuo.generator.enums.LogLevelEnums; 4 | import com.github.zhuyizhuo.generator.mybatis.generator.extension.LogService; 5 | import com.github.zhuyizhuo.generator.mybatis.vo.GenerateInfo; 6 | 7 | import java.util.Properties; 8 | 9 | /** 10 | * 日志输出工具类
11 | * time: 2018/8/6 11:04 12 | * 13 | * @author zhuo
14 | * @version 1.0 15 | */ 16 | public class LogUtils { 17 | 18 | private static LogLevelEnums logLevel = LogLevelEnums.INFO; 19 | private static LogService logService; 20 | 21 | /** 22 | * 设置打印日志的 service 23 | * @param logService 日志级别 24 | */ 25 | public static void setLogService(LogService logService) { 26 | LogUtils.logService = logService; 27 | } 28 | 29 | /** 30 | * 设置日志级别 31 | * @param level 日志级别 32 | * @since 1.5.1 33 | */ 34 | public static void setLevel(LogLevelEnums level) { 35 | LogUtils.logLevel = level; 36 | } 37 | 38 | /** 39 | * 设置日志级别 40 | * @param level 日志级别 41 | * @since 1.5.0 42 | */ 43 | public static void setLevel(String level) { 44 | try{ 45 | LogUtils.logLevel = LogLevelEnums.valueOf(level); 46 | } catch (Exception e){ 47 | LogUtils.logLevel = LogLevelEnums.INFO; 48 | } 49 | } 50 | 51 | /** 52 | * 打印 debug 日志 53 | * @param info 日志内容 54 | */ 55 | public static void debug(String info){ 56 | if (LogLevelEnums.DEBUG.getLevel() >= getLevel()){ 57 | System.out.println(info); 58 | } 59 | } 60 | 61 | /** 62 | * 打印 info 日志 63 | * @param info 日志内容 64 | */ 65 | public static void info(String info){ 66 | if (LogLevelEnums.INFO.getLevel() >= getLevel()){ 67 | System.out.println(info); 68 | } 69 | } 70 | 71 | /** 72 | * 打印错误日志 73 | * @param errorMsg 错误信息 74 | */ 75 | public static void error(String errorMsg){ 76 | if (LogLevelEnums.INFO.getLevel() >= getLevel()){ 77 | System.err.println(errorMsg); 78 | } 79 | } 80 | 81 | /** 82 | * 打印堆栈信息 需要日志级别在 DEBUG 以下 83 | * @param e 异常类 84 | */ 85 | public static void printException(Exception e){ 86 | if (LogLevelEnums.DEBUG.getLevel() >= getLevel()){ 87 | e.printStackTrace(); 88 | } 89 | } 90 | 91 | /** 92 | * 打印生成器对象 93 | * @param generateInfo 输出到模板的元数据对象 94 | */ 95 | public static void logGenerateInfo(GenerateInfo generateInfo){ 96 | if (LogLevelEnums.INFO.getLevel() >= getLevel() && logService != null){ 97 | logService.logGenerateInfo(generateInfo); 98 | } 99 | } 100 | 101 | public static void logProperties(String message, Properties properties) { 102 | if (LogLevelEnums.INFO.getLevel() >= getLevel()){ 103 | System.out.println(message); 104 | for (String key : properties.stringPropertyNames()) { 105 | System.out.println(key + "=" + properties.getProperty(key)); 106 | } 107 | } 108 | } 109 | 110 | public static void debug(String message, Properties properties) { 111 | if (LogLevelEnums.DEBUG.getLevel() >= getLevel()){ 112 | System.out.println(message); 113 | for (String key : properties.stringPropertyNames()) { 114 | System.out.println(key + "=" + properties.getProperty(key)); 115 | } 116 | } 117 | } 118 | 119 | /** 120 | * 获取日志级别 121 | * @return 当前日志级别 122 | */ 123 | private static int getLevel(){ 124 | return logLevel.getLevel(); 125 | } 126 | 127 | 128 | } 129 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/utils/PathUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.utils; 2 | 3 | /** 4 | * 路径工具类 5 | * 6 | * @author zhuo 7 | * @since 1.5.0 8 | */ 9 | public class PathUtils { 10 | 11 | private final char match; 12 | 13 | public PathUtils(char match) { 14 | this.match = match; 15 | } 16 | 17 | private boolean matches(char c) { 18 | return c == match; 19 | } 20 | 21 | /** 22 | * Returns a string copy of the input character sequence, with each group of consecutive matching 23 | * BMP characters replaced by a single replacement character. For example: 24 | * 25 | *
{@code
26 |      * CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-')
27 |      * }
28 | * 29 | * ... returns {@code "b-p-r"}. 30 | * 31 | * @param sequence the character sequence to replace matching groups of characters in 32 | * @param replacement the character to append to the result string in place of each group of 33 | * matching characters in {@code sequence} 34 | * @return the new string 35 | */ 36 | public String collapseFrom(CharSequence sequence, char replacement) { 37 | // This implementation avoids unnecessary allocation. 38 | int len = sequence.length(); 39 | for (int i = 0; i < len; i++) { 40 | char c = sequence.charAt(i); 41 | if (matches(c)) { 42 | if (c == replacement && (i == len - 1 || !matches(sequence.charAt(i + 1)))) { 43 | // a no-op replacement 44 | i++; 45 | } else { 46 | StringBuilder builder = new StringBuilder(len).append(sequence, 0, i).append(replacement); 47 | return finishCollapseFrom(sequence, i + 1, len, replacement, builder, true); 48 | } 49 | } 50 | } 51 | // no replacement needed 52 | return sequence.toString(); 53 | } 54 | 55 | private String finishCollapseFrom( 56 | CharSequence sequence, 57 | int start, 58 | int end, 59 | char replacement, 60 | StringBuilder builder, 61 | boolean inMatchingGroup) { 62 | for (int i = start; i < end; i++) { 63 | char c = sequence.charAt(i); 64 | if (matches(c)) { 65 | if (!inMatchingGroup) { 66 | builder.append(replacement); 67 | inMatchingGroup = true; 68 | } 69 | } else { 70 | builder.append(c); 71 | inMatchingGroup = false; 72 | } 73 | } 74 | return builder.toString(); 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/utils/PropertiesUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.utils; 2 | 3 | import com.github.zhuyizhuo.generator.exception.GeneratorException; 4 | import com.github.zhuyizhuo.generator.mybatis.generator.support.ContextHolder; 5 | import org.apache.ibatis.io.Resources; 6 | 7 | import java.io.BufferedReader; 8 | import java.io.InputStreamReader; 9 | import java.nio.charset.StandardCharsets; 10 | import java.util.Properties; 11 | 12 | /** 13 | * 资源文件处理工具类 14 | * @author zhuo 15 | * @version 1.0 16 | * time: 2018/7/29 18:39 17 | */ 18 | public class PropertiesUtils { 19 | /** 自定义配置 */ 20 | public static final Properties customConfiguration = new Properties(); 21 | 22 | /** 23 | * 加载配置文件 24 | * @param configPath 配置文件路径 25 | */ 26 | public static Properties loadProperties(String configPath) throws GeneratorException { 27 | try { 28 | if (GeneratorStringUtils.isBlank(configPath)) { 29 | return customConfiguration; 30 | } 31 | return loadProperties(new BufferedReader(new InputStreamReader(Resources.getResourceAsStream(configPath), StandardCharsets.UTF_8))); 32 | } catch (Exception e){ 33 | LogUtils.printException(e); 34 | throw new GeneratorException("加载配置文件失败,path:" + configPath+",Exception:" + e.getMessage()); 35 | } 36 | } 37 | 38 | /** 39 | * 加载配置文件 40 | */ 41 | public static Properties loadProperties(BufferedReader resourceAsStream) { 42 | try { 43 | customConfiguration.load(resourceAsStream); 44 | return customConfiguration; 45 | } catch (Exception e) { 46 | LogUtils.printException(e); 47 | throw new GeneratorException("加载配置文件失败!"); 48 | } 49 | } 50 | 51 | public static String getProperties(String key){ 52 | String property = customConfiguration.getProperty(key); 53 | return property == null ? null : property.trim(); 54 | } 55 | 56 | /** 57 | * 获取配置信息 58 | * @param key 键 59 | * @return 不存在或配置有误 返回 FALSE 60 | */ 61 | public static boolean getBooleanConfigDefaultFalse(String key){ 62 | try { 63 | return Boolean.parseBoolean(ContextHolder.getConfig(key)); 64 | } catch(Exception e) { 65 | LogUtils.info("key:"+key+" 配置有误,有效值为 true 或 false!"); 66 | return false; 67 | } 68 | } 69 | 70 | /** 71 | * 获取配置信息 72 | * @param key 键 73 | * @return 不存在则 返回TRUE 74 | */ 75 | public static boolean getBooleanConfigDefaultTrue(String key){ 76 | try { 77 | return Boolean.parseBoolean(ContextHolder.getConfig(key)); 78 | } catch(Exception e) { 79 | LogUtils.info("key:"+key+" 配置有误,有效值为 true 或 false!"); 80 | return true; 81 | } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/utils/SqlSessionUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.utils; 2 | 3 | import org.apache.ibatis.io.Resources; 4 | import org.apache.ibatis.session.SqlSession; 5 | import org.apache.ibatis.session.SqlSessionFactory; 6 | import org.apache.ibatis.session.SqlSessionFactoryBuilder; 7 | 8 | import java.io.InputStream; 9 | 10 | /** 11 | * 获取 SqlSession
12 | * time: 2018/7/30 12:34 13 | * 14 | * @author zhuo
15 | * @version 1.0 16 | */ 17 | public class SqlSessionUtils { 18 | 19 | /** 20 | * 相对路径加载配置文件 21 | * @return SqlSession instance 22 | */ 23 | public static SqlSession getSqlSession() throws RuntimeException { 24 | try { 25 | //配置文件 26 | String resource = "mybatis/mybatis-config.xml"; 27 | InputStream inputStream = Resources.getResourceAsStream(resource); 28 | SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, PropertiesUtils.customConfiguration); 29 | return sqlSessionFactory.openSession(); 30 | } catch (Exception e){ 31 | throw new RuntimeException("SqlSessionUtils.getSqlSession Exception",e); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/github/zhuyizhuo/generator/utils/TypeConversion.java: -------------------------------------------------------------------------------- 1 | package com.github.zhuyizhuo.generator.utils; 2 | 3 | import com.github.zhuyizhuo.generator.enums.ErrorTypeEnums; 4 | import org.apache.ibatis.type.JdbcType; 5 | 6 | import java.math.BigDecimal; 7 | import java.time.LocalDateTime; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Objects; 11 | 12 | /** 13 | *

类型转换器

14 | * time : 2018/7/29 18:36 15 | * @author zhuo 16 | * @version 1.0 17 | */ 18 | public class TypeConversion { 19 | /** 20 | * key 数据库字段类型 21 | * value java 数据类型 22 | * 注意: 23 | * 如果 java 数据类型非 java.lang 包下的类, 24 | * 则需要在 javaDataTypeFullPathMap 中须有对应的全路径配置 25 | */ 26 | public static final Map dbDataType2JavaType = new HashMap<>(); 27 | /** 28 | * key java 数据类型 29 | * value 该类型全路径 30 | * 即 import 的 java 类全路径 31 | */ 32 | public static final Map javaDataTypeFullPathMap = new HashMap<>(); 33 | /** 34 | * key 数据库字段类型 key 必须大写 35 | * value mybatis JDBC type 36 | */ 37 | public static final Map type2JdbcTypeMap = new HashMap<>(); 38 | /** 39 | * key java 数据类型 40 | * value mybatis 内置对应别名 41 | */ 42 | public static final Map parameterTypeMap = new HashMap<>(); 43 | 44 | static{ 45 | initDBDataType2JavaMap(); 46 | 47 | initType2JdbcTypeMap(); 48 | 49 | initParameterTypeMap(); 50 | } 51 | 52 | private static void initParameterTypeMap() { 53 | /** 基本数据类型 */ 54 | addParameterType("byte","_byte"); 55 | addParameterType("long","_long"); 56 | addParameterType("short","_short"); 57 | addParameterType("int","_int"); 58 | addParameterType("double","_double"); 59 | addParameterType("float","_float"); 60 | addParameterType("boolean","_boolean"); 61 | /** 对象类型 */ 62 | addParameterType("String","string"); 63 | addParameterType("Byte","byte"); 64 | addParameterType("Long","long"); 65 | addParameterType("Short","short"); 66 | addParameterType("Integer","int"); 67 | addParameterType("Double","double"); 68 | addParameterType("Float","float"); 69 | addParameterType("Boolean","boolean"); 70 | addParameterType("Date","date"); 71 | addParameterType("BigDecimal","bigdecimal"); 72 | } 73 | 74 | private static void initType2JdbcTypeMap() { 75 | addType2JdbcType("INT", JdbcType.INTEGER); 76 | addType2JdbcType("NUMBER", JdbcType.NUMERIC); 77 | addType2JdbcType("BIT", JdbcType.NUMERIC); 78 | addType2JdbcType("TIMESTAMP(6)", JdbcType.TIMESTAMP); 79 | addType2JdbcType("TIMESTAMP", JdbcType.TIMESTAMP); 80 | addType2JdbcType("DATETIME", JdbcType.TIMESTAMP); 81 | addType2JdbcType("VARCHAR", JdbcType.VARCHAR); 82 | addType2JdbcType("VARCHAR2", JdbcType.VARCHAR); 83 | addType2JdbcType("NVARCHAR2", JdbcType.NVARCHAR); 84 | addType2JdbcType("DATE", JdbcType.TIMESTAMP); 85 | addType2JdbcType("DECIMAL", JdbcType.DECIMAL); 86 | addType2JdbcType("DOUBLE", JdbcType.DOUBLE); 87 | addType2JdbcType("FLOAT", JdbcType.FLOAT); 88 | addType2JdbcType("BIGINT", JdbcType.BIGINT); 89 | addType2JdbcType("SMALLINT", JdbcType.SMALLINT); 90 | addType2JdbcType("TINYINT", JdbcType.TINYINT); 91 | addType2JdbcType("NUMERIC", JdbcType.NUMERIC); 92 | addType2JdbcType("TEXT", JdbcType.VARCHAR); 93 | addType2JdbcType("NCLOB", JdbcType.NCLOB); 94 | addType2JdbcType("CLOB", JdbcType.CLOB); 95 | addType2JdbcType("BLOB", JdbcType.BLOB); 96 | } 97 | 98 | private static void initDBDataType2JavaMap() { 99 | setDBDataType2JavaClass("CHAR",String.class); 100 | setDBDataType2JavaClass("NUMBER",Integer.class); 101 | setDBDataType2JavaClass("LONG",Long.class); 102 | setDBDataType2JavaClass("VARCHAR2",String.class); 103 | setDBDataType2JavaClass("NVARCHAR2",String.class); 104 | setDBDataType2JavaClass("CLOB",String.class); 105 | setDBDataType2JavaClass("NCLOB",String.class); 106 | setDBDataType2JavaClass("BLOB",String.class); 107 | setDBDataType2JavaClass("INT",Integer.class); 108 | setDBDataType2JavaClass("VARCHAR",String.class); 109 | setDBDataType2JavaClass("TEXT",String.class); 110 | setDBDataType2JavaClass("LONGTEXT",String.class); 111 | setDBDataType2JavaClass("LONGBLOB",String.class); 112 | setDBDataType2JavaClass("TINYBLOB",String.class); 113 | setDBDataType2JavaClass("TINYTEXT",String.class); 114 | setDBDataType2JavaClass("BIT",Integer.class); 115 | setDBDataType2JavaClass("TINYINT",Integer.class); 116 | setDBDataType2JavaClass("BIGINT",Long.class); 117 | setDBDataType2JavaClass("DECIMAL", BigDecimal.class); 118 | setDBDataType2JavaClass("FLOAT", BigDecimal.class); 119 | setDBDataType2JavaClass("DOUBLE", BigDecimal.class); 120 | setDBDataType2JavaClass("DATE", LocalDateTime.class); 121 | setDBDataType2JavaClass("TIME", LocalDateTime.class); 122 | setDBDataType2JavaClass("DATETIME", LocalDateTime.class); 123 | setDBDataType2JavaClass("YEAR", LocalDateTime.class); 124 | setDBDataType2JavaClass("FLOAT", BigDecimal.class); 125 | setDBDataType2JavaClass("TIMESTAMP", LocalDateTime.class); 126 | setDBDataType2JavaClass("TIMESTAMP(6)", LocalDateTime.class); 127 | 128 | } 129 | 130 | /** 131 | * 生成实体时 需要 import 的引用类型在此设置 132 | * @param dbDataType 数据库字段类型 133 | * @param clazz java 类型 134 | */ 135 | private static void setDBDataType2JavaClass(String dbDataType, Class clazz) { 136 | addDBDataType2JavaType(dbDataType, clazz.getSimpleName()); 137 | addJavaDataTypeFullPath(clazz); 138 | } 139 | 140 | /** 141 | * 根据 dbDataType 转大写后去 map 取值, 如果值不存在返回 dbDataType 142 | * @param dbDataType 根据 dbDataType 转大写后去 map 取值 143 | * @return 根据 dbDataType 转大写后去 map 取值, 如果值不存在返回 dbDataType 144 | */ 145 | public static String getJavaTypeByDBDataType(String dbDataType) { 146 | if (GeneratorStringUtils.isBlank(dbDataType)){ 147 | return ""; 148 | } 149 | String javaDataType = dbDataType2JavaType.get(dbDataType.toUpperCase()); 150 | if (GeneratorStringUtils.isNotBlank(javaDataType)){ 151 | return javaDataType; 152 | } 153 | throw new UnsupportedOperationException(ErrorTypeEnums.NOT_SUPPORT_DB_DATATYPE.getMessage(dbDataType)); 154 | } 155 | 156 | public static String type2JdbcType(String dbColmType) { 157 | if (GeneratorStringUtils.isBlank(dbColmType)){ 158 | return ""; 159 | } 160 | String jdbcType = type2JdbcTypeMap.get(dbColmType.toUpperCase()); 161 | if (GeneratorStringUtils.isNotBlank(jdbcType)){ 162 | return jdbcType; 163 | } 164 | throw new UnsupportedOperationException(ErrorTypeEnums.NOT_SUPPORT_DATATYPE_JDBC_TYPE.getMessage(dbColmType)); 165 | } 166 | 167 | /** 168 | * 根据 java 数据类型 获取 mybatis parameter 类型 169 | * @param javaDataType java 数据类型 170 | * @return mybatis parameter 类型 171 | */ 172 | public static String getMybatisParameterTypeByJavaDataType(String javaDataType) { 173 | if (GeneratorStringUtils.isBlank(javaDataType)){ 174 | return ""; 175 | } 176 | String mybatisParameterType = parameterTypeMap.get(javaDataType); 177 | if (GeneratorStringUtils.isNotBlank(mybatisParameterType)){ 178 | return mybatisParameterType; 179 | } 180 | return javaDataType; 181 | } 182 | 183 | public static void addJavaDataTypeFullPath(Class value){ 184 | String simpleName = value.getSimpleName(); 185 | if (javaDataTypeFullPathMap.containsKey(simpleName)){ 186 | return; 187 | } 188 | String name = value.getName(); 189 | if (name.startsWith("java.lang.") && name.split("\\.").length == 3){ 190 | return; 191 | } 192 | javaDataTypeFullPathMap.put(simpleName, name); 193 | } 194 | 195 | /** 196 | * 配置 java 类型和 mybatis parameterType 映射关系 197 | * @param javaDataType java 数据类型 198 | * @param parameterType mybatis parameterType 199 | */ 200 | public static void addParameterType(String javaDataType, String parameterType) { 201 | parameterTypeMap.put(javaDataType, parameterType); 202 | } 203 | 204 | public static void addDBDataType2JavaType(String dbDataType, String javaType) { 205 | dbDataType2JavaType.put(dbDataType.toUpperCase(), javaType); 206 | } 207 | 208 | public static void addType2JdbcType(String dataBaseType, JdbcType jdbcType) { 209 | if (Objects.nonNull(dataBaseType)){ 210 | type2JdbcTypeMap.put(dataBaseType.toUpperCase(), jdbcType.toString()); 211 | } 212 | } 213 | 214 | /** 215 | * 初始化 216 | */ 217 | public static void init(Map> typeMapper) { 218 | if (typeMapper != null && !typeMapper.isEmpty()) { 219 | for (Map.Entry> entry : typeMapper.entrySet()) { 220 | //java 类型对应 parameterType 的全路径 221 | Class clazz = entry.getValue(); 222 | addParameterType(clazz.getSimpleName(), clazz.getName()); 223 | 224 | setDBDataType2JavaClass(entry.getKey(), entry.getValue()); 225 | } 226 | } 227 | } 228 | 229 | } 230 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/batchInsert.ftl: -------------------------------------------------------------------------------- 1 | /** 2 | * ${methodDescription.BATCH_INSERT.comment}
3 | <#list methodDescription.BATCH_INSERT.params as param> 4 | * @param ${javaClassDefinition.MODEL.className?uncap_first}List ${param.comment}
5 | 6 | * @return 新增的数据条数 7 | */ 8 | int ${methodDescription.BATCH_INSERT.methodName}(List<${javaClassDefinition.MODEL.className}> ${javaClassDefinition.MODEL.className?uncap_first}List); 9 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/countByWhere.ftl: -------------------------------------------------------------------------------- 1 | /** 2 | * ${methodDescription.COUNT_BY_WHERE.comment}
3 | <#list methodDescription.COUNT_BY_WHERE.params as param> 4 | * @param ${javaClassDefinition.MODEL.className?uncap_first} ${param.comment}
5 | 6 | * @return 符合条件的数据总数 7 | */ 8 | int ${methodDescription.COUNT_BY_WHERE.methodName}(${javaClassDefinition.MODEL.className} ${javaClassDefinition.MODEL.className?uncap_first}); 9 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/deleteByPrimaryKey.ftl: -------------------------------------------------------------------------------- 1 | <#if tableInfo.singlePrimaryKey> 2 | /** 3 | * ${methodDescription.DELETE_BY_PRIMARY_KEY.comment}
4 | * @param ${tableInfo.primaryKeyColumns[0].javaColumnName?uncap_first} ${tableInfo.primaryKeyColumns[0].columnComment}
5 | * @return 删除的数据条数 6 | */ 7 | int ${methodDescription.DELETE_BY_PRIMARY_KEY.methodName}(${tableInfo.primaryKeyColumns[0].javaDataType} ${tableInfo.primaryKeyColumns[0].javaColumnName?uncap_first}); 8 | <#else> 9 | /** 10 | * ${methodDescription.DELETE_BY_PRIMARY_KEY.comment}
11 | <#list methodDescription.DELETE_BY_PRIMARY_KEY.params as param> 12 | * @param ${javaClassDefinition.MODEL.className?uncap_first} ${param.comment}
13 | 14 | * @return 删除的数据条数 15 | */ 16 | int ${methodDescription.DELETE_BY_PRIMARY_KEY.methodName}(${javaClassDefinition.MODEL.className} ${javaClassDefinition.MODEL.className?uncap_first}); 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/deleteByWhere.ftl: -------------------------------------------------------------------------------- 1 | /** 2 | * ${methodDescription.DELETE_BY_WHERE.comment}
3 | <#list methodDescription.DELETE_BY_WHERE.params as param> 4 | * @param ${javaClassDefinition.MODEL.className?uncap_first} ${param.comment}
5 | 6 | * @return 删除的数据条数 7 | */ 8 | int ${methodDescription.DELETE_BY_WHERE.methodName}(${javaClassDefinition.MODEL.className} ${javaClassDefinition.MODEL.className?uncap_first}); 9 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/insert.ftl: -------------------------------------------------------------------------------- 1 | /** 2 | * ${methodDescription.INSERT.comment}
3 | <#list methodDescription.INSERT.params as param> 4 | * @param ${javaClassDefinition.MODEL.className?uncap_first} ${param.comment}
5 | 6 | * @return 新增的数据条数 7 | */ 8 | int ${methodDescription.INSERT.methodName}(${javaClassDefinition.MODEL.className} ${javaClassDefinition.MODEL.className?uncap_first}); 9 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/model.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MODEL.fullPackage}; 2 | 3 | <#list tableInfo.importPackages as import> 4 | <#if import??> 5 | import ${import}; 6 | 7 | 8 | 9 | /** 10 | * ${tableInfo.tableComment!}
11 | * 12 | * @author ${classCommentInfo.author}
13 | * @date ${classCommentInfo.createTime}
14 | * @since ${classCommentInfo.sinceVersion}
15 | */ 16 | public class ${javaClassDefinition.MODEL.className} { 17 | 18 | <#list tableInfo.columnLists as colm> 19 | <#if colm??> 20 | /** ${colm.columnComment} */ 21 | private ${colm.javaDataType} ${colm.javaColumnName}; 22 | 23 | 24 | 25 | <#list tableInfo.columnLists as colm> 26 | <#if colm??> 27 | public ${colm.javaDataType} get${colm.javaColumnName?cap_first}() { 28 | return ${colm.javaColumnName}; 29 | } 30 | 31 | public void set${colm.javaColumnName?cap_first}(${colm.javaDataType} ${colm.javaColumnName}) { 32 | this.${colm.javaColumnName} = ${colm.javaColumnName}; 33 | } 34 | 35 | 36 | 37 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/model_lombok.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MODEL.fullPackage}; 2 | 3 | import lombok.Data; 4 | 5 | <#list tableInfo.importPackages as import> 6 | <#if import??> 7 | import ${import}; 8 | 9 | 10 | 11 | /** 12 | * ${tableInfo.tableComment!}
13 | * 14 | * @author ${classCommentInfo.author}
15 | * @date ${classCommentInfo.createTime}
16 | * @since ${classCommentInfo.sinceVersion}
17 | */ 18 | @Data 19 | public class ${javaClassDefinition.MODEL.className} { 20 | 21 | <#list tableInfo.columnLists as colm> 22 | <#if colm??> 23 | /** ${colm.columnComment} */ 24 | private ${colm.javaDataType} ${colm.javaColumnName}; 25 | 26 | 27 | 28 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/queryByPrimaryKey.ftl: -------------------------------------------------------------------------------- 1 | <#if tableInfo.singlePrimaryKey> 2 | /** 3 | * ${methodDescription.QUERY_BY_PRIMARY_KEY.comment}
4 | * @param ${tableInfo.primaryKeyColumns[0].javaColumnName?uncap_first} ${tableInfo.primaryKeyColumns[0].columnComment}
5 | * @return ${javaClassDefinition.MODEL.className} 数据对象 6 | */ 7 | ${javaClassDefinition.MODEL.className} ${methodDescription.QUERY_BY_PRIMARY_KEY.methodName}(${tableInfo.primaryKeyColumns[0].javaDataType} ${tableInfo.primaryKeyColumns[0].javaColumnName?uncap_first}); 8 | <#else> 9 | /** 10 | * ${methodDescription.QUERY_BY_PRIMARY_KEY.comment}
11 | <#list methodDescription.QUERY_BY_PRIMARY_KEY.params as param> 12 | * @param ${javaClassDefinition.MODEL.className?uncap_first} ${param.comment}
13 | 14 | * @return ${javaClassDefinition.MODEL.className} 数据对象 15 | */ 16 | ${javaClassDefinition.MODEL.className} ${methodDescription.QUERY_BY_PRIMARY_KEY.methodName}(${javaClassDefinition.MODEL.className} ${javaClassDefinition.MODEL.className?uncap_first}); 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/queryByWhere.ftl: -------------------------------------------------------------------------------- 1 | /** 2 | * ${methodDescription.QUERY_BY_WHERE.comment}
3 | <#list methodDescription.QUERY_BY_WHERE.params as param> 4 | * @param ${javaClassDefinition.MODEL.className?uncap_first} ${param.comment}
5 | 6 | * @return 符合条件的数据集合 7 | */ 8 | List<${javaClassDefinition.MODEL.className}> ${methodDescription.QUERY_BY_WHERE.methodName}(${javaClassDefinition.MODEL.className} ${javaClassDefinition.MODEL.className?uncap_first}); 9 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/updateByPrimaryKey.ftl: -------------------------------------------------------------------------------- 1 | /** 2 | * ${methodDescription.UPDATE_BY_PRIMARY_KEY.comment}
3 | <#list methodDescription.UPDATE_BY_PRIMARY_KEY.params as param> 4 | * @param ${javaClassDefinition.MODEL.className?uncap_first} ${param.comment}
5 | 6 | * @return 更新的数据条数 7 | */ 8 | int ${methodDescription.UPDATE_BY_PRIMARY_KEY.methodName}(${javaClassDefinition.MODEL.className} ${javaClassDefinition.MODEL.className?uncap_first}); 9 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/common/vo_swagger_lombok.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.VO.fullPackage}; 2 | 3 | import io.swagger.annotations.ApiModelProperty; 4 | import lombok.Data; 5 | 6 | import java.io.Serializable; 7 | <#list tableInfo.importPackages as import> 8 | <#if import??> 9 | import ${import}; 10 | 11 | 12 | 13 | /** 14 | * ${tableInfo.tableComment!}
15 | * 16 | * @author ${classCommentInfo.author}
17 | * @date ${classCommentInfo.createTime}
18 | * @since ${classCommentInfo.sinceVersion}
19 | */ 20 | @Data 21 | public class ${javaClassDefinition.VO.className} implements Serializable { 22 | private static final long serialVersionUID=1L; 23 | 24 | <#list tableInfo.columnLists as colm> 25 | <#if colm??> 26 | /** ${colm.columnComment} */ 27 | @ApiModelProperty(value = "${colm.columnComment}") 28 | private ${colm.javaDataType} ${colm.javaColumnName}; 29 | 30 | 31 | 32 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/mybatis_plus/mapper_mybatis_plus.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MAPPER.fullPackage}; 2 | 3 | 4 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 5 | import ${javaClassDefinition.MODEL.fullPackage}.${javaClassDefinition.MODEL.className}; 6 | import org.apache.ibatis.annotations.Mapper; 7 | 8 | /** 9 | * ${tableInfo.tableComment!} Mapper 10 | * 11 | * @author ${classCommentInfo.author}
12 | * @date ${classCommentInfo.createTime}
13 | * @since ${classCommentInfo.sinceVersion}
14 | */ 15 | @Mapper 16 | public interface ${javaClassDefinition.MAPPER.className} extends BaseMapper<${javaClassDefinition.MODEL.className}> { 17 | 18 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/mybatis_plus/model_mybatis_plus.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MODEL.fullPackage}; 2 | 3 | import com.baomidou.mybatisplus.annotation.TableId; 4 | import com.baomidou.mybatisplus.annotation.TableName; 5 | 6 | import java.io.Serializable; 7 | <#list tableInfo.importPackages as import> 8 | <#if import??> 9 | import ${import}; 10 | 11 | 12 | 13 | /** 14 | * ${tableInfo.tableComment!}
15 | * 16 | * @author ${classCommentInfo.author}
17 | * @date ${classCommentInfo.createTime}
18 | * @since ${classCommentInfo.sinceVersion}
19 | */ 20 | @TableName("${tableInfo.tableName}") 21 | public class ${javaClassDefinition.MODEL.className} implements Serializable { 22 | private static final long serialVersionUID=1L; 23 | <#list tableInfo.primaryKeyColumns as colm> 24 | <#if colm??> 25 | /** ${colm.columnComment} */ 26 | @TableId 27 | private ${colm.javaDataType} ${colm.javaColumnName}; 28 | 29 | 30 | <#list tableInfo.columnLists as colm> 31 | <#if colm??> 32 | <#if (colm_index >= tableInfo.primaryKeyColumns?size)> 33 | /** ${colm.columnComment} */ 34 | private ${colm.javaDataType} ${colm.javaColumnName}; 35 | 36 | 37 | 38 | 39 | <#list tableInfo.columnLists as colm> 40 | <#if colm??> 41 | public ${colm.javaDataType} get${colm.javaColumnName?cap_first}() { 42 | return ${colm.javaColumnName}; 43 | } 44 | 45 | public void set${colm.javaColumnName?cap_first}(${colm.javaDataType} ${colm.javaColumnName}) { 46 | this.${colm.javaColumnName} = ${colm.javaColumnName}; 47 | } 48 | 49 | 50 | 51 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/mybatis_plus/model_mybatis_plus_lombok.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MODEL.fullPackage}; 2 | 3 | import com.baomidou.mybatisplus.annotation.TableId; 4 | import com.baomidou.mybatisplus.annotation.TableName; 5 | import lombok.Data; 6 | 7 | import java.io.Serializable; 8 | <#list tableInfo.importPackages as import> 9 | <#if import??> 10 | import ${import}; 11 | 12 | 13 | 14 | /** 15 | * ${tableInfo.tableComment}
16 | * 17 | * @author ${classCommentInfo.author}
18 | * @since ${classCommentInfo.sinceVersion}
19 | */ 20 | @Data 21 | @TableName("${tableInfo.tableName}") 22 | public class ${javaClassDefinition.MODEL.className} implements Serializable { 23 | private static final long serialVersionUID=1L; 24 | <#list tableInfo.primaryKeyColumns as colm> 25 | <#if colm??> 26 | /** ${colm.columnComment} */ 27 | @TableId 28 | private ${colm.javaDataType} ${colm.javaColumnName}; 29 | 30 | 31 | <#list tableInfo.columnLists as colm> 32 | <#if colm??> 33 | <#if (colm_index >= tableInfo.primaryKeyColumns?size)> 34 | /** ${colm.columnComment} */ 35 | private ${colm.javaDataType} ${colm.javaColumnName}; 36 | 37 | 38 | 39 | 40 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/mybatis_plus/service_impl_mybatis_plus.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.SERVICE_IMPL.fullPackage}; 2 | 3 | import org.springframework.stereotype.Service; 4 | import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; 5 | 6 | import ${javaClassDefinition.MAPPER.fullPackage}.${javaClassDefinition.MAPPER.className}; 7 | import ${javaClassDefinition.MODEL.fullPackage}.${javaClassDefinition.MODEL.className}; 8 | import ${javaClassDefinition.SERVICE.fullPackage}.${javaClassDefinition.SERVICE.className}; 9 | 10 | /** 11 | * ${tableInfo.tableComment!} Service 实现类 12 | * 13 | * @author ${classCommentInfo.author}
14 | * @date ${classCommentInfo.createTime}
15 | * @since ${classCommentInfo.sinceVersion}
16 | */ 17 | @Service("${javaClassDefinition.SERVICE_IMPL.className?uncap_first}") 18 | public class ${javaClassDefinition.SERVICE_IMPL.className} extends ServiceImpl<${javaClassDefinition.MAPPER.className}, ${javaClassDefinition.MODEL.className}> implements ${javaClassDefinition.SERVICE.className} { 19 | 20 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/mybatis_plus/service_mybatis_plus.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.SERVICE.fullPackage}; 2 | 3 | import com.baomidou.mybatisplus.extension.service.IService; 4 | import ${javaClassDefinition.MODEL.fullPackage}.${javaClassDefinition.MODEL.className}; 5 | 6 | /** 7 | * ${tableInfo.tableComment!} Service 8 | * 9 | * @author ${classCommentInfo.author}
10 | * @date ${classCommentInfo.createTime}
11 | * @since ${classCommentInfo.sinceVersion}
12 | */ 13 | public interface ${javaClassDefinition.SERVICE.className} extends IService<${javaClassDefinition.MODEL.className}> { 14 | 15 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/mybatis_plus/xml_mybatis_plus.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | <#list mybatisXmlDefinition.columns as colm> 7 | <#if colm??> 8 | <#if colm.primaryKey> 9 | 10 | <#else> 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/no_primary_key_mysql_mapper_template.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MAPPER.fullPackage}; 2 | 3 | import java.util.List; 4 | 5 | import ${javaClassDefinition.MODEL.fullPackage}.${javaClassDefinition.MODEL.className}; 6 | 7 | /** 8 | * ${tableInfo.tableComment!} dao layer interface
9 | * 10 | * @author ${classCommentInfo.author}
11 | * @date ${classCommentInfo.createTime}
12 | * @since ${classCommentInfo.sinceVersion}
13 | */ 14 | public interface ${javaClassDefinition.MAPPER.className} { 15 | <#if methodDescription.INSERT.enabled> 16 | 17 | <#include "common/insert.ftl"/> 18 | 19 | <#if methodDescription.DELETE_BY_WHERE.enabled> 20 | 21 | <#include "common/deleteByWhere.ftl"/> 22 | 23 | <#if methodDescription.QUERY_BY_WHERE.enabled> 24 | 25 | <#include "common/queryByWhere.ftl"/> 26 | 27 | <#if methodDescription.COUNT_BY_WHERE.enabled> 28 | 29 | <#include "common/countByWhere.ftl"/> 30 | 31 | <#if methodDescription.BATCH_INSERT.enabled> 32 | 33 | <#include "common/batchInsert.ftl"/> 34 | 35 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/no_primary_key_oracle_mapper_template.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MAPPER.fullPackage}; 2 | 3 | import java.util.List; 4 | 5 | import ${javaClassDefinition.MODEL.fullPackage}.${javaClassDefinition.MODEL.className}; 6 | 7 | /** 8 | * ${tableInfo.tableComment!} dao layer interface
9 | * 10 | * @author ${classCommentInfo.author}
11 | * @date ${classCommentInfo.createTime}
12 | * @since ${classCommentInfo.sinceVersion}
13 | */ 14 | public interface ${javaClassDefinition.MAPPER.className} { 15 | <#if methodDescription.INSERT.enabled> 16 | 17 | <#include "common/insert.ftl"/> 18 | 19 | <#if methodDescription.DELETE_BY_WHERE.enabled> 20 | 21 | <#include "common/deleteByWhere.ftl"/> 22 | 23 | <#if methodDescription.QUERY_BY_WHERE.enabled> 24 | 25 | <#include "common/queryByWhere.ftl"/> 26 | 27 | <#if methodDescription.COUNT_BY_WHERE.enabled> 28 | 29 | <#include "common/countByWhere.ftl"/> 30 | 31 | <#if methodDescription.BATCH_INSERT.enabled> 32 | 33 | <#include "common/batchInsert.ftl"/> 34 | 35 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/primary_key_mysql_mapper_template.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MAPPER.fullPackage}; 2 | 3 | import java.util.List; 4 | 5 | import ${javaClassDefinition.MODEL.fullPackage}.${javaClassDefinition.MODEL.className}; 6 | 7 | /** 8 | * ${tableInfo.tableComment!} dao layer interface
9 | * 10 | * @author ${classCommentInfo.author}
11 | * @date ${classCommentInfo.createTime}
12 | * @since ${classCommentInfo.sinceVersion}
13 | */ 14 | public interface ${javaClassDefinition.MAPPER.className} { 15 | <#if methodDescription.INSERT.enabled> 16 | 17 | <#include "common/insert.ftl"/> 18 | 19 | <#if methodDescription.DELETE_BY_PRIMARY_KEY.enabled> 20 | 21 | <#include "common/deleteByPrimaryKey.ftl"/> 22 | 23 | <#if methodDescription.DELETE_BY_WHERE.enabled> 24 | 25 | <#include "common/deleteByWhere.ftl"/> 26 | 27 | <#if methodDescription.UPDATE_BY_PRIMARY_KEY.enabled> 28 | 29 | <#include "common/updateByPrimaryKey.ftl"/> 30 | 31 | <#if methodDescription.QUERY_BY_PRIMARY_KEY.enabled> 32 | 33 | <#include "common/queryByPrimaryKey.ftl"/> 34 | 35 | <#if methodDescription.QUERY_BY_WHERE.enabled> 36 | 37 | <#include "common/queryByWhere.ftl"/> 38 | 39 | <#if methodDescription.COUNT_BY_WHERE.enabled> 40 | 41 | <#include "common/countByWhere.ftl"/> 42 | 43 | <#if methodDescription.BATCH_INSERT.enabled> 44 | 45 | <#include "common/batchInsert.ftl"/> 46 | 47 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/java/primary_key_oracle_mapper_template.ftl: -------------------------------------------------------------------------------- 1 | package ${javaClassDefinition.MAPPER.fullPackage}; 2 | 3 | import java.util.List; 4 | 5 | import ${javaClassDefinition.MODEL.fullPackage}.${javaClassDefinition.MODEL.className}; 6 | 7 | /** 8 | * ${tableInfo.tableComment!} dao layer interface
9 | * 10 | * @author ${classCommentInfo.author}
11 | * @date ${classCommentInfo.createTime}
12 | * @since ${classCommentInfo.sinceVersion}
13 | */ 14 | public interface ${javaClassDefinition.MAPPER.className} { 15 | <#if methodDescription.INSERT.enabled> 16 | 17 | <#include "common/insert.ftl"/> 18 | 19 | <#if methodDescription.DELETE_BY_PRIMARY_KEY.enabled> 20 | 21 | <#include "common/deleteByPrimaryKey.ftl"/> 22 | 23 | <#if methodDescription.DELETE_BY_WHERE.enabled> 24 | 25 | <#include "common/deleteByWhere.ftl"/> 26 | 27 | <#if methodDescription.UPDATE_BY_PRIMARY_KEY.enabled> 28 | 29 | <#include "common/updateByPrimaryKey.ftl"/> 30 | 31 | <#if methodDescription.QUERY_BY_PRIMARY_KEY.enabled> 32 | 33 | <#include "common/queryByPrimaryKey.ftl"/> 34 | 35 | <#if methodDescription.QUERY_BY_WHERE.enabled> 36 | 37 | <#include "common/queryByWhere.ftl"/> 38 | 39 | <#if methodDescription.COUNT_BY_WHERE.enabled> 40 | 41 | <#include "common/countByWhere.ftl"/> 42 | 43 | <#if methodDescription.BATCH_INSERT.enabled> 44 | 45 | <#include "common/batchInsert.ftl"/> 46 | 47 | } -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/common_sql_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | <#list mybatisXmlDefinition.columns as colm> 4 | <#if colm??> 5 | 6 | AND ${colm.columnName} = ${'#'}{${colm.javaColumnName}} 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/count_by_where_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | 6 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/delete_by_primary_key_xml.ftl: -------------------------------------------------------------------------------- 1 | <#assign parameterType = "${tableInfo.singlePrimaryKey?then(mybatisXmlDefinition.columns[0].parameterType,mybatisXmlDefinition.parameterType)}"> 2 | 3 | 4 | DELETE FROM ${tableInfo.tableName} 5 | WHERE <#list tableInfo.primaryKeyColumns as colm><#if colm_index != 0>AND ${colm.columnName} = ${'#{'}${colm.javaColumnName}} 6 | 7 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/delete_by_where_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | DELETE FROM ${tableInfo.tableName} 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/insert_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | INSERT INTO ${tableInfo.tableName} ( 4 | 5 | <#list mybatisXmlDefinition.columns as colm> 6 | <#if colm??> 7 | ${colm.columnName}, 8 | 9 | 10 | 11 | ) VALUES ( 12 | 13 | <#list mybatisXmlDefinition.columns as colm> 14 | <#if colm??> 15 | ${'#'}{${colm.javaColumnName},jdbcType=${colm.jdbcType}}, 16 | 17 | 18 | 19 | ) 20 | 21 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/mysql_batch_insert_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | INSERT INTO ${tableInfo.tableName} ( 4 | 5 | <#list mybatisXmlDefinition.columns as colm> 6 | <#if colm??> 7 | ${colm.columnName}, 8 | 9 | 10 | 11 | ) VALUES 12 | 13 | ( 14 | 15 | <#list mybatisXmlDefinition.columns as colm> 16 | <#if colm??> 17 | ${'#'}{item.${colm.javaColumnName},jdbcType=${colm.jdbcType}}, 18 | 19 | 20 | 21 | ) 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/oracle_batch_insert_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | INSERT All 4 | 5 | INTO ${tableInfo.tableName} ( 6 | 7 | <#list mybatisXmlDefinition.columns as colm> 8 | <#if colm??> 9 | ${colm.columnName}, 10 | 11 | 12 | 13 | ) VALUES ( 14 | 15 | <#list mybatisXmlDefinition.columns as colm> 16 | <#if colm??> 17 | ${'#'}{item.${colm.javaColumnName},jdbcType=${colm.jdbcType}}, 18 | 19 | 20 | 21 | ) 22 | 23 | SELECT 1 FROM DUAL 24 | 25 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/query_by_primary_key_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | <#if tableInfo.singlePrimaryKey> 3 | 6 | 7 | SELECT 8 | <#list mybatisXmlDefinition.columns as colm> 9 | <#if colm??> 10 | <#if colm_has_next> 11 | ${colm.columnName}, 12 | <#else> 13 | ${colm.columnName} 14 | 15 | 16 | 17 | FROM ${tableInfo.tableName} 18 | WHERE 19 | <#list tableInfo.primaryKeyColumns as colm> 20 | <#if colm_index != 0>AND ${colm.columnName} = ${'#{'}${colm.javaColumnName}} 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/query_by_where_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | 16 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/result_map_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | <#list mybatisXmlDefinition.columns as colm> 3 | <#if colm??> 4 | <#if colm.primaryKey> 5 | 6 | <#else> 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/common/update_by_primary_key_xml.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | UPDATE ${tableInfo.tableName} 4 | 5 | <#list tableInfo.columnLists as colm> 6 | <#if colm??> 7 | <#if (colm_index >= tableInfo.primaryKeyColumns?size)> 8 | ${colm.columnName} = ${'#{'}${colm.javaColumnName}}, 9 | 10 | 11 | 12 | 13 | WHERE 14 | <#list tableInfo.primaryKeyColumns as colm> 15 | <#if colm_index != 0>AND ${colm.columnName} = ${'#{'}${colm.javaColumnName}} 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/no_primary_key_mysql_mybatis_template.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <#include "common/result_map_xml.ftl"/> 6 | 7 | <#include "common/common_sql_xml.ftl"/> 8 | <#if methodDescription.INSERT.enabled> 9 | 10 | <#include "common/insert_xml.ftl"/> 11 | 12 | <#if methodDescription.DELETE_BY_WHERE.enabled> 13 | 14 | <#include "common/delete_by_where_xml.ftl"/> 15 | 16 | <#if methodDescription.QUERY_BY_WHERE.enabled> 17 | 18 | <#include "common/query_by_where_xml.ftl"/> 19 | 20 | <#if methodDescription.COUNT_BY_WHERE.enabled> 21 | 22 | <#include "common/count_by_where_xml.ftl"/> 23 | 24 | <#if methodDescription.BATCH_INSERT.enabled> 25 | 26 | <#include "common/mysql_batch_insert_xml.ftl"/> 27 | 28 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/no_primary_key_oracle_mybatis_template.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <#include "common/result_map_xml.ftl"/> 6 | 7 | <#include "common/common_sql_xml.ftl"/> 8 | <#if methodDescription.INSERT.enabled> 9 | 10 | <#include "common/insert_xml.ftl"/> 11 | 12 | <#if methodDescription.DELETE_BY_WHERE.enabled> 13 | 14 | <#include "common/delete_by_where_xml.ftl"/> 15 | 16 | <#if methodDescription.QUERY_BY_WHERE.enabled> 17 | 18 | <#include "common/query_by_where_xml.ftl"/> 19 | 20 | <#if methodDescription.COUNT_BY_WHERE.enabled> 21 | 22 | <#include "common/count_by_where_xml.ftl"/> 23 | 24 | <#if methodDescription.BATCH_INSERT.enabled> 25 | 26 | <#include "common/oracle_batch_insert_xml.ftl"/> 27 | 28 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/primary_key_mysql_mybatis_template.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <#include "common/result_map_xml.ftl"/> 6 | 7 | <#include "common/common_sql_xml.ftl"/> 8 | <#if methodDescription.INSERT.enabled> 9 | 10 | <#include "common/insert_xml.ftl"/> 11 | 12 | <#if methodDescription.DELETE_BY_PRIMARY_KEY.enabled> 13 | 14 | <#include "common/delete_by_primary_key_xml.ftl"/> 15 | 16 | <#if methodDescription.DELETE_BY_WHERE.enabled> 17 | 18 | <#include "common/delete_by_where_xml.ftl"/> 19 | 20 | <#if methodDescription.UPDATE_BY_PRIMARY_KEY.enabled> 21 | 22 | <#include "common/update_by_primary_key_xml.ftl"/> 23 | 24 | <#if methodDescription.QUERY_BY_PRIMARY_KEY.enabled> 25 | 26 | <#include "common/query_by_primary_key_xml.ftl"/> 27 | 28 | <#if methodDescription.QUERY_BY_WHERE.enabled> 29 | 30 | <#include "common/query_by_where_xml.ftl"/> 31 | 32 | <#if methodDescription.COUNT_BY_WHERE.enabled> 33 | 34 | <#include "common/count_by_where_xml.ftl"/> 35 | 36 | <#if methodDescription.BATCH_INSERT.enabled> 37 | 38 | <#include "common/mysql_batch_insert_xml.ftl"/> 39 | 40 | -------------------------------------------------------------------------------- /src/main/resources/freemarker/template/xml/primary_key_oracle_mybatis_template.ftl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | <#include "common/result_map_xml.ftl"/> 6 | 7 | <#include "common/common_sql_xml.ftl"/> 8 | <#if methodDescription.INSERT.enabled> 9 | 10 | <#include "common/insert_xml.ftl"/> 11 | 12 | <#if methodDescription.DELETE_BY_PRIMARY_KEY.enabled> 13 | 14 | <#include "common/delete_by_primary_key_xml.ftl"/> 15 | 16 | <#if methodDescription.DELETE_BY_WHERE.enabled> 17 | 18 | <#include "common/delete_by_where_xml.ftl"/> 19 | 20 | <#if methodDescription.UPDATE_BY_PRIMARY_KEY.enabled> 21 | 22 | <#include "common/update_by_primary_key_xml.ftl"/> 23 | 24 | <#if methodDescription.QUERY_BY_PRIMARY_KEY.enabled> 25 | 26 | <#include "common/query_by_primary_key_xml.ftl"/> 27 | 28 | <#if methodDescription.QUERY_BY_WHERE.enabled> 29 | 30 | <#include "common/query_by_where_xml.ftl"/> 31 | 32 | <#if methodDescription.COUNT_BY_WHERE.enabled> 33 | 34 | <#include "common/count_by_where_xml.ftl"/> 35 | 36 | <#if methodDescription.BATCH_INSERT.enabled> 37 | 38 | <#include "common/oracle_batch_insert_xml.ftl"/> 39 | 40 | -------------------------------------------------------------------------------- /src/main/resources/generate-config.properties: -------------------------------------------------------------------------------- 1 | ########## 必选配置 start ########### 2 | # MYSQL 数据库配置 3 | # db.type=MYSQL 4 | # db.driver=com.mysql.cj.jdbc.Driver 5 | # db.url=jdbc:mysql://localhost:3306/test?useUnicode=true&serverTimezone=Asia/Shanghai 6 | # db.table-schema=test 7 | # db.username=root 8 | # db.password=root 9 | 10 | # ORACLE 数据库配置 11 | # db.type=ORACLE 12 | # db.driver=oracle.jdbc.driver.OracleDriver 13 | # db.url=jdbc:oracle:thin:@192.168.0.1:1521:test 14 | # db.table-schema=schema 15 | # db.username=root 16 | # db.password=root 17 | ########## 必选配置 end ########### 18 | 19 | ############### 建议配置 start ############ 20 | # 指定生成的表 多张表用英文逗号隔开,大小写不敏感,缺省配置为 db.table-schema 下的全部表 21 | generate.table-names=table1,table2 22 | # java 类生成的公共包路径,无缺省值 23 | generate.base.package= 24 | ############### 建议配置 end ############ 25 | 26 | ############### 公共配置 start ############ 27 | # 是否生成各模块完整包目录。默认为 true。如过配置为 false,则仅生成包名最后一层目录 28 | # 和 generate.base.out-put-path 配置项一起使用 将文件生成至指定文件夹 可有效减少目录层级 29 | generate.java.base.package.enabled=true 30 | # 生成文件输出公共路径,缺省配置为系统变量 user.dir 路径下 31 | generate.base.out-put-path=#{user.dir} 32 | # java 类生成的公共目录 33 | generate.base.java-path=/src/main/java/ 34 | ############### 公共配置 end ############ 35 | 36 | ############### 类配置 start ############ 37 | # CONTROLLER 包名 38 | generate.java.module.controller.package=#{generate.base.package}.controller 39 | # CONTROLLER 名称 默认配置 {0}Controller,{0} 表示表名转为驼峰命名 40 | generate.java.module.controller.name-format={0}Controller 41 | # CONTROLLER 输出路径 42 | generate.java.module.controller.out-put-path=#{generate.base.out-put-path}/#{generate.base.java-path}>#{generate.java.module.controller.package} 43 | 44 | # 视图对象包名 45 | generate.java.module.vo.package=#{generate.base.package}.vo 46 | # 视图对象名称 默认配置 {0} 即表名转为驼峰命名 47 | generate.java.module.vo.name-format={0} 48 | # 视图对象类输出路径 49 | generate.java.module.vo.out-put-path=#{generate.base.out-put-path}/#{generate.base.java-path}>#{generate.java.module.vo.package} 50 | 51 | # SERVICE 包名 52 | generate.java.module.service.package=#{generate.base.package}.service 53 | # SERVICE 名称 默认配置 {0}Service {0} 表示表名转为驼峰命名 54 | generate.java.module.service.name-format={0}Service 55 | # SERVICE 输出路径 56 | generate.java.module.service.out-put-path=#{generate.base.out-put-path}/#{generate.base.java-path}>#{generate.java.module.service.package} 57 | 58 | # ServiceImpl 包名 59 | generate.java.module.service.impl.package=#{generate.base.package}.service.impl 60 | # ServiceImpl 名称 默认配置 {0}ServiceImpl {0} 表示表名转为驼峰命名 61 | generate.java.module.service.impl.name-format={0}ServiceImpl 62 | # ServiceImpl 输出路径 63 | generate.java.module.service.impl.out-put-path=#{generate.base.out-put-path}/#{generate.base.java-path}>#{generate.java.module.service.impl.package} 64 | 65 | # MAPPER 包名 66 | generate.java.module.mapper.package=#{generate.base.package}.mapper 67 | # MAPPER 名称 默认配置 {0}Mapper {0} 表示表名转为驼峰命名 68 | generate.java.module.mapper.name-format={0}Mapper 69 | # MAPPER 输出路径 70 | generate.java.module.mapper.out-put-path=#{generate.base.out-put-path}/#{generate.base.java-path}>#{generate.java.module.mapper.package} 71 | 72 | # 实体类包名 73 | generate.java.module.model.package=#{generate.base.package}.model 74 | # 实体名称 默认配置 {0} 即表名转为驼峰命名 75 | generate.java.module.model.name-format={0} 76 | # 实体类输出路径 77 | generate.java.module.model.out-put-path=#{generate.base.out-put-path}/#{generate.base.java-path}>#{generate.java.module.model.package} 78 | ############### 类配置 end ############ 79 | 80 | ##################### XML 配置 start #################### 81 | # XML 名称 默认 驼峰命名 82 | generate.resources.xml.name-format={0} 83 | # 生成资源文件输出路径 路径请使用/或\\分隔 84 | generate.resources.xml.out-put-path=#{generate.base.out-put-path}/src/main/resources/xml 85 | # mybatis xml 的 parameterType 别名是否启用 86 | generate.resources.xml.mybatis.parameter-type.aliases.enabled=false 87 | ##################### XML 配置 end #################### 88 | 89 | ############## 注释 start ############## 90 | # 作者 默认 @author : TODO 91 | generate.java.comment.author=TODO 92 | # 创建版本号 默认 @since : 1.0 93 | generate.java.comment.since-version=1.0 94 | # 当前版本号 默认 @version : 1.0 95 | generate.java.comment.current-version=1.0 96 | ############## 注释 end ################ 97 | 98 | ############### 方法配置 start ############### 99 | # 新增数据,默认生成该方法 配置为 false 则不生成 100 | generate.java.method.insert.enabled=true 101 | # 方法描述 102 | generate.java.method.insert.comment=\u65b0\u589e\u6570\u636e 103 | # 方法名格式化 104 | generate.java.method.insert.name-format=insert 105 | 106 | # 批量新增数据,默认生成该方法 配置为 false 则不生成 107 | generate.java.method.batch-insert.enabled=true 108 | generate.java.method.batch-insert.comment=\u6279\u91cf\u63d2\u5165\u6570\u636e 109 | generate.java.method.batch-insert.name-format=insertBatch 110 | 111 | # 根据传入参数删除数据,默认生成该方法 配置为 false 则不生成 112 | generate.java.method.delete-by-where.enabled=true 113 | generate.java.method.delete-by-where.comment=\u6839\u636e\u4f20\u5165\u53c2\u6570\u5220\u9664\u6570\u636e 114 | generate.java.method.delete-by-where.name-format=delete 115 | 116 | # 根据主键删除数据,默认生成该方法 配置为 false 则不生成; 如果表无主键 则不生成此方法 117 | generate.java.method.delete-by-primary-key.enabled=true 118 | generate.java.method.delete-by-primary-key.comment=\u6839\u636e\u4e3b\u952e\u5220\u9664\u6570\u636e 119 | generate.java.method.delete-by-primary-key.name-format=deleteByPrimaryKey 120 | 121 | # 根据主键更新数据,默认生成该方法 配置为 false 则不生成; 如果表无主键 则不生成此方法 122 | generate.java.method.update-by-primary-key.enabled=true 123 | generate.java.method.update-by-primary-key.comment=\u6839\u636e\u4e3b\u952e\u66f4\u65b0\u6570\u636e 124 | generate.java.method.update-by-primary-key.name-format=updateByPrimaryKey 125 | 126 | # 根据传入参数查询数据列表,默认生成该方法 配置为 false 则不生成 127 | generate.java.method.query-by-where.enabled=true 128 | generate.java.method.query-by-where.comment=\u6839\u636e\u4f20\u5165\u53c2\u6570\u67e5\u8be2\u6570\u636e\u5217\u8868 129 | generate.java.method.query-by-where.name-format=selectList 130 | 131 | # 根据主键查询数据,默认生成该方法 配置为 false 则不生成; 如果表无主键 则不生成此方法 132 | generate.java.method.select-one-by-primary-key.enabled=true 133 | generate.java.method.select-one-by-primary-key.comment=\u6839\u636e\u4e3b\u952e\u67e5\u8be2\u6570\u636e 134 | generate.java.method.select-one-by-primary-key.name-format=selectOne 135 | 136 | # 统计符合条件的数据数量,默认生成该方法 配置为 false 则不生成 137 | generate.java.method.count-by-where.enabled=true 138 | generate.java.method.count-by-where.comment=\u7edf\u8ba1\u7b26\u5408\u6761\u4ef6\u7684\u6570\u636e\u6570\u91cf 139 | generate.java.method.count-by-where.name-format=selectCount 140 | ############### 方法配置 end ############### 141 | 142 | ##################### 其他配置 start #################### 143 | # 数据库表名分隔符 例如表名为 SHOP_USER 则分隔符为 _ 缺省配置为 _ 144 | generate.table.separator=_ 145 | # 数据库字段分隔符 例如字段为 ORDER_NO 则分隔符为 _ 缺省配置为 _ 146 | generate.table.field.separator=_ 147 | 148 | # 日志级别 INFO DEBUG 默认 INFO 149 | generate.log.level=INFO 150 | ##################### 其他配置 end #################### 151 | 152 | # 注意事项 153 | # 所有 java 模块的 out-put-path ,包结构则需以 > 开头,否则将作为目录名处理 154 | # 例如生成路径配置为 /v1.2>com.github.generator 155 | # 则真实路径为 /v1.2/com/github/generator 156 | # 也可直接配置为目录 /v1.2/com/github/generator -------------------------------------------------------------------------------- /src/main/resources/generator.properties: -------------------------------------------------------------------------------- 1 | generate.convention.sourceType=com.github.zhuyizhuo.generator.mybatis.convention.ClassCommentInfo,\ 2 | com.github.zhuyizhuo.generator.mybatis.convention.FileOutPathInfo -------------------------------------------------------------------------------- /src/main/resources/mybatis/mappers/MysqlDataBaseMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 24 | 25 | 42 | 43 | 61 | 62 | -------------------------------------------------------------------------------- /src/main/resources/mybatis/mappers/OracleDataBaseMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 34 | 35 | 61 | 62 | 77 | 78 | -------------------------------------------------------------------------------- /src/main/resources/mybatis/mybatis-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 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 | --------------------------------------------------------------------------------