├── .gitignore ├── .idea ├── encodings.xml ├── uiDesigner.xml └── vcs.xml ├── LICENSE ├── README.md ├── code-builder-core ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── gitee │ └── hengboy │ └── builder │ ├── common │ ├── CodeBuilderProperties.java │ ├── enums │ │ ├── DbTypeEnum.java │ │ ├── EngineTypeEnum.java │ │ ├── ErrorEnum.java │ │ ├── JavaTypeEnum.java │ │ └── TableMetaDataEnum.java │ ├── exception │ │ └── CodeBuilderException.java │ └── util │ │ └── StringUtil.java │ └── core │ ├── configuration │ ├── BuilderConfiguration.java │ └── TemplateConfiguration.java │ ├── database │ ├── AbstractDataBase.java │ ├── DataBase.java │ ├── DataBaseFactory.java │ ├── impl │ │ ├── Db2DataBase.java │ │ ├── MySqlDataBase.java │ │ ├── OracleDataBase.java │ │ ├── PostgreSqlDataBase.java │ │ └── SqlServerDataBase.java │ └── model │ │ ├── Column.java │ │ ├── Key.java │ │ ├── Table.java │ │ └── util │ │ ├── JavaTypeResolver.java │ │ ├── Jdbc4Types.java │ │ └── JdbcTypeResolver.java │ ├── engine │ ├── AbstractEngineTemplate.java │ ├── EngineTemplate.java │ ├── EngineTemplateFactory.java │ ├── impl │ │ └── FreemarkerEngineImpl.java │ └── model │ │ └── DataModelEntity.java │ └── invoke │ └── CodeBuilderInvoke.java ├── code-builder-maven-plugin-sample ├── pom.xml └── src │ └── main │ └── resources │ └── templates │ └── builder │ └── freemarker │ └── entity.ftl ├── code-builder-maven-plugin ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── gitee │ └── hengboy │ └── builder │ └── CodeBuilderMojo.java ├── code-builder-spring-boot-autoconfigure ├── pom.xml └── src │ └── main │ ├── java │ └── com │ │ └── gitee │ │ └── hengboy │ │ └── builder │ │ └── spring │ │ └── boot │ │ └── autoconfigure │ │ ├── BuilderAutoConfigureProperties.java │ │ └── CodeBuilderAutoConfiguration.java │ └── resources │ └── META-INF │ ├── spring-configuration-metadata.json │ └── spring.factories ├── code-builder-spring-boot-starter-sample ├── pom.xml └── src │ └── main │ └── resources │ ├── application.yml │ └── templates │ └── builder │ └── freemarker │ └── entity.ftl ├── code-builder-spring-boot-starter └── pom.xml └── pom.xml /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | 21 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 22 | hs_err_pid* 23 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/uiDesigner.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /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, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "{}" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright 2018 恒宇少年 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 欢迎使用代码生成器Code-Builder 2 | 3 | #### 更新记录 4 | 5 | - 1.0.5.RELEASE 6 | - 添加模板前缀参数`filePrefix` 7 | - 修改项目根地址排除`target` 8 | - 生成完成后输出本次执行信息 9 | 10 | 11 | #### Maven Center 版本 12 | [![Maven central](https://maven-badges.herokuapp.com/maven-central/com.gitee.hengboy/code-builder-spring-boot-starter/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.gitee.hengboy/code-builder-spring-boot-starter) 13 | 14 | ### 欢迎关注公众号 15 | 16 | ![微信公众号](http://resource.hengboy.com/image/qrcode.jpg) 17 | 关注微信公众号,回复`加群`,获取交流群群号。 18 | 19 | ### 背景 20 | 本来`code-builder`是专门为`MyBatis Enhance`来编写的一块代码生成器 21 | ### code-builder可以用来做什么? 22 | `code-builder`是一款代码生成`maven mojo`插件,通过简单的配置就可以完成数据库内`Table`转换`Entity`或者其他实体类,想怎么生成完全根据你的个人业务逻辑,`code-builder`尽可能的完善的提供数据库内的一些定义的信息,让你更方便更灵活的来生成`Java`文件。 23 | 24 | ### 使用环境 25 | - `Maven`构建的项目 26 | - `JDK 1.6`以上版本 27 | 28 | ### 实现方式 29 | 30 | #### 是怎么获取到的数据库信息? 31 | `code-builder`内部采用了`java.sql.Connection`的`MetaData`元数据的方式来获取数据库内`Table`、`Column`等信息,`MetaData`是不局限于任何的数据库类型的,所以`code-builder`在基础设计上是可以在任何数据库类型中来完成它的生成任务的,不过初版本仅支持了`MySQL`、`MariaDB`这两种数据库类型,在`code-builder`后期更新版本中会把主流的数据库进行添加。 32 | 33 | #### 生成模板选型 34 | 目前`code-builder`内部采用了`freemarker`模板来完成实体类的自动生成,模板由使用者来自定义编写,内部预留了使用其他模板的方式,如果你需要使用别的模板,如:`Velocity`,对应添加生成的实现业务逻辑即可。 35 | 36 | ### 怎么配置? 37 | #### SpringBoot 方式配置 38 | 在`1.0.5.RELEASE`版本添加了集成`SpringBoot`的`starter`,依赖如下所示: 39 | - 使用`Maven`构建工具时,复制下面的内容到`pom.xml`配置文件内 40 | ``` 41 | 42 | com.gitee.hengboy 43 | code-builder-spring-boot-starter 44 | 1.0.5.RELEASE 45 | 46 | ``` 47 | - 如果你是用的`Gradle`构建工具,那么复制下面的内容到你的`build.gradle` 48 | ``` 49 | compile group: 'com.gitee.hengboy', name: 'code-builder-spring-boot-starter', version: '1.0.5.RELEASE' 50 | ``` 51 | 那么我们在`application.yml`或者`application.properties`配置文件内该怎么配置相关的参数呢? 52 | ``` 53 | hengboy: 54 | code: 55 | builder: 56 | execute: true 57 | configuration: 58 | package-prefix: com.code.builder.sample.codebuildersample 59 | templates: 60 | - 61 | name: entity.ftl 62 | packageName: model 63 | fileSuffix: Entity 64 | - 65 | name: service.ftl 66 | packageName: service 67 | fileSuffix: Service 68 | - 69 | name: controller.ftl 70 | packageName: controller 71 | fileSuffix: Controller 72 | generator-by-pattern: '%app_user_info%' 73 | db-type: mysql 74 | engine-type-enum: freemarker 75 | builder-dir: classes.templates.builder 76 | target-dir: generated-sources.java 77 | tables: 78 | - app_shop_type 79 | - app_user_exchange_good 80 | ignore-class-prefix: App 81 | ``` 82 | > 每个参数的具体介绍请往下看。 83 | #### Maven Plugin 方式配置 84 | 由于`code-builder`是`Maven mojo`插件的形式创建的,所以我们只需要在项目的`pom.xml`文件内添加`plugin`插件配置,如下所示: 85 | ``` 86 | 87 | com.gitee.hengboy 88 | code-builder-maven-plugin 89 | 1.0.5.RELEASE 90 | 91 | 92 | 93 | generator 94 | 95 | 96 | 97 | 98 | 99 | mysql 100 | mysql-connector-java 101 | 5.1.46 102 | 103 | 104 | 105 | true 106 | MySQL 107 | com.mysql.jdbc.Driver 108 | xxxx 109 | xxxx 110 | xxxxx 111 | jdbc:mysql://xxx.xx.xx.xx:3306 112 | 113 | app_shop_type
114 | app_user_exchange_good
115 |
116 | FREEMARKER 117 | %app_user_info% 118 | App 119 | classes.templates.builder 120 | 121 | com.code.builder.sample 122 | 123 | 127 | 132 | 137 | 138 | 139 |
140 |
141 | ``` 142 | #### 数据库驱动依赖添加 143 | `code-builder`不局限你使用的数据库类型,所以在生成时需要使用者添加对应数据类型的依赖,如上面的配置中则是添加了`MySQL`数据库的依赖 144 | ``` 145 | ..... 146 | 147 | 148 | mysql 149 | mysql-connector-java 150 | 5.1.46 151 | 152 | 153 | ..... 154 | ``` 155 | #### 生成的控制开关 156 | 并不是每一次的`编译`或者`打包`时都需要生成对应的实体,针对这种情况`code-builder`添加了`execute`参数来控制开启与关闭。 157 | - `true`:开启自动生成 158 | - `false`:关闭自动生成 159 | 160 | #### 数据库类型配置 161 | 执行自动生成前需要配置数据库的相关配置信息 162 | - `dbType`:数据库类型,默认使用`MySQL`数据库类型。 163 | - `dbDriverClassName`:数据库驱动类名,根据不用的数据库类型配置不同的驱动类名,默认根据`dbType`使用内部定义的类名,如需自定义可以设置。`(仅maven-plugin使用)` 164 | 165 | #### 数据库基本信息配置 (仅maven-plugin使用) 166 | - `dbName`:数据库名称 167 | - `dbUserName`:数据库用户名 168 | - `dbPassword`:数据库密码 169 | - `dbUrl`:数据库连接路径,连接路径不需要填写数据库名,正确示例如:`jdbc:mysql://localhost:3306` 170 | #### 生成表名符合规则的表 171 | 根据表达式来创建表,表达式与模糊查询语句表达式一般无二,配置`generatorByPattern`参数并设置对应的表达式就可以根据表达式来匹配出参与生成的`Table`列表。 172 | - 指定前缀匹配 173 | ``` 174 | app_order% 175 | ``` 176 | 示例:将会匹配出`app_order_info`、`app_order_record`等表。 177 | - 指定后缀匹配 178 | ``` 179 | %order 180 | ``` 181 | 示例:将会匹配出`app_good_order`、`app_exchange_order`等表。 182 | - 包含匹配 183 | ``` 184 | %order% 185 | ``` 186 | 示例:将会匹配出`app_order_info`、`app_good_order`等表。 187 | #### 生成指定表 188 | `code-builder`支持指定单个或者多个表来生成,只需要配置`tables`参数即可,如下所示: 189 | ``` 190 | 191 | app_shop_type
192 | app_user_exchange_good
193 |
194 | ``` 195 | 上面的配置是本次生成仅操作`app_shop_type`、`app_user_exchange_good`两张表。 196 | > 注意:`tables`参数的优先级要高于`generatorByPattern`参数。 197 | 198 | 199 | #### 自定义builder所需模板路径 200 | `code-builder`会自动去找`classes/templates/builder`下的模板,如果使用默认的`freemarker`模板来生成,那么模板所存放的位置为`classes/templates/builder/freemarker`。 201 | 如果你想自定义模板的路径可以设置`builderDir`的地址,在这里因为考虑到了不同操作系统的分隔符不一样(`Windows`系统分隔符`\`,`Linux`以及`O SX`分隔符为`/`)所以这里采用`.`分隔符配置,`code-builder`会自动根据操作系统来转换路径,配置如下所示: 202 | ``` 203 | classes.code.builder 204 | ``` 205 | 206 | > 注意:`freemarker`文件夹不允许修改,只能修改`code-builder`加载模板的根路径。 207 | #### 排除生成实体后的前缀 208 | 数据库设计有时需要添加前缀,如:`app_`、`sys_`等,实际生成实体后前缀则是并不想展示,那么配置参数`ignoreClassPrefix`就可以自动排除前缀,如下所示: 209 | ``` 210 | App 211 | ``` 212 | > 注意:由于替换生成后的类名称所以这里要准守驼峰命名规则首字母大写,一次只能配置一个替换前缀。 213 | 214 | 使用前`AppUserInfoEntity`,使用后`UserInfoEntity`。 215 | 216 | #### 模板配置 217 | 使用`templates`标签配置自定义的模板列表,一次可以使用单个或者多个模板进行生成,如下配置: 218 | ``` 219 | 220 | 225 | 230 | 235 | 236 | ``` 237 | - `name` :`freemarker`目录下模板的名称,`必填` 238 | - `packageName`:生成该模板文件后的子包名称,`非必填` 239 | - `fileSuffix`:生成文件的后缀,如:配置后缀为`Entity`,则添加后缀后的文件名为`UserInfoEntity`,后缀首字母会自动根据驼峰转换成大写 240 | 241 | ### 内置参数 242 | 模板驱动数据模型内置了部分参数,`code-builder`准备的每一个参数都是在生成实体类时都可能会用到的。 243 | #### Table参数 244 | - `tableName` `表名`,数据类型:`java.lang.String` 245 | - `remark` `表备注信息`,数据类型:`java.lang.String` 246 | - `entityName` `实体类名称`,如:`user_info`转换为`userInfo`,数据类型:`java.lang.String` 247 | - `columns` `列列表`,数据类型:`java.util.List` 248 | - `primaryKeys` `主键列表`,数据类型:`java.util.List` 249 | - `hasSqlDate` 是否存在`java.sql.Date`类型,`true`:存在,`false`:不存在,数据类型:`java.lang.Boolean` 250 | - `hasTimeStamp` 是否存在`java.sql.TimeStamp`类型,`true`:存在,`false`:不存在,数据类型:`java.lang.Boolean` 251 | - `hasBigDecimal` 是否存在`java.math.BigDecimal`类型,`true`:存在,`false`:不存在,数据类型:`java.lang.Boolean` 252 | 253 | ##### 使用方式 254 | > `freemarker模板`:`${table.xxx}`,如表名的使用为`${table.tableName}` 255 | 256 | #### Column参数 257 | - `columnName` `列名`,如:`user_id`,数据类型:`java.lang.String` 258 | - `primaryKey` `是否为主键`,数据类型:`java.lang.Boolean`,`true`:主键,`false`:非主键 259 | - `foreignKey` `是否为外键`,数据类型:`java.lang.Boolean`,`true`:外键,`false`:非外键 260 | - `size` `列长度`,数据类型:`java.lang.Integer` 261 | - `decimalDigits` `小数点精度`,数据类型:`java.lang.Integer` 262 | - `nullable` `列是否为空`,数据类型:`java.lang.Boolean`,`true`:为空,`false`:非空 263 | - `autoincrement` `是否自增`,数据类型:`java.lang.Boolean`,`true`:自增列,`false`:普通列 264 | - `defaultValue` `默认值`,数据类型:`java.lang.String` 265 | - `remark` `列备注`,数据类型:`java.lang.String` 266 | - `jdbcType` `JDBC类型`,对应`java.sql.Types`内类型,数据类型:`java.lang.Integer` 267 | - `jdbcTypeName` `JDBC类型名称`,数据类型:`java.lang.String` 268 | - `javaProperty` `格式化后的属性名称`,如:`userId`,数据类型:`java.lang.String` 269 | - `javaType` `Java数据类型短名`,如:`TimeStamp`,数据类型:`java.lang.String` 270 | - `fullJavaType` `Java数据类型全名`,如:`java.sql.TimeStamp`,数据类型:`java.lang.String` 271 | ##### 使用方式 272 | > `freemarker模板`:`${column.xxx}`,如列名的使用为`${column.columnName}` 273 | #### 基础参数 274 | - `className`:Class名称,freemarker指定模板生成文件的类名,模板内配置`${className}`使用 275 | - `packageName`:Package名称,freemarker指定模板生成文件的包名,模板内配置`${packageName}`使用 276 | ### 怎么自定义模板? 277 | 下面提供一个简单的模板示例,根据上面的`内置参数`可以任意自定义生成文件的内容。 278 | ``` 279 | <#if (packageName)??> 280 | package ${packageName}; 281 | 282 | import lombok.Data; 283 | 284 | <#if (table.hasSqlDate)> 285 | import java.sql.Date; 286 | 287 | <#if (table.hasTimeStamp)> 288 | import java.sql.Timestamp; 289 | 290 | <#if (table.hasBigDecimal)> 291 | import java.math.BigDecimal; 292 | 293 | /** 294 | *

本类代码由code-builder自动生成

295 | *

表名: ${table.tableName} - ${table.remark}

296 | * =============================== 297 | * Created with code-builder. 298 | * User:恒宇少年 299 | * Date:${.now} 300 | * 简书:http://www.jianshu.com/u/092df3f77bca 301 | * 码云:https://gitee.com/hengboy 302 | * ================================ 303 | */ 304 | @Data 305 | public class ${className} { 306 | <#list table.primaryKeys as key> 307 | /** 308 | * ${key.columnName} - ${key.remark} 309 | */ 310 | private ${key.javaType} ${key.javaProperty}; 311 | 312 | <#list table.columns as column> 313 | <#if (!column.primaryKey)> 314 | /** 315 | * ${column.columnName} - ${column.remark} 316 | */ 317 | private ${column.javaType} ${column.javaProperty}; 318 | 319 | 320 | } 321 | ``` 322 | 上面是一个数据实体的`freemarker`模板内容,把这个模板存放到`freemarker`目录下,对应在`templates`标签内添加配置就可以完成数据实体的自动创建,创建后的数据实体内容如下所示: 323 | ``` 324 | package com.code.builder.sample.model; 325 | import lombok.Data; 326 | 327 | import java.sql.Timestamp; 328 | /** 329 | *

本类代码由code-builder自动生成

330 | *

表名: app_balance_type - 余额类型信息表

331 | * =============================== 332 | * Created with code-builder. 333 | * User:恒宇少年 334 | * Date:Jul 17, 2018 9:09:13 PM 335 | * 简书:http://www.jianshu.com/u/092df3f77bca 336 | * 码云:https://gitee.com/hengboy 337 | * ================================ 338 | */ 339 | @Data 340 | public class BalanceTypeEntity { 341 | /** 342 | * BT_ID - 余额类型主键 343 | */ 344 | private String btId; 345 | /** 346 | * BT_NAME - 余额类型名称 347 | */ 348 | private String btName; 349 | /** 350 | * BT_FLAG - 余额类型标识 351 | */ 352 | private String btFlag; 353 | /** 354 | * BT_CREATE_TIME - 添加时间 355 | */ 356 | private Timestamp btCreateTime; 357 | /** 358 | * BT_MARK - 余额类型备注信息 359 | */ 360 | private String btMark; 361 | } 362 | ``` 363 | ### 创建的实体类去了哪里? 364 | 创建的实体类会在`target/generated-sources/java`目录下,如果你配置`packagePrefix`参数,会自动在生成目录下创建`packagePrefix`配置值的子目录。 365 | 如: 366 | ``` 367 | com.code.builder.sample 368 | ``` 369 | 则最终创建的生成根目录为:`target/generated-sources/java/com/code/builder/sample` 370 | ### 怎么使用? 371 | #### SpringBoot 方式使用 372 | 1. `运行项目`就可以根据配置生成对应的文件 373 | #### Maven Plugin 方式使用 374 | 1. 执行`mvn clean`命令用于清空`target`目录下的内容 375 | 2. 执行`mvn compile`命令编译项目并且生成`实体类` 376 | 377 | ### 为什么SpringBoot方式不用配置数据库信息? 378 | `Maven Plugin`方式是通过配置的`数据库连接信息`以及数据库连接驱动获取数据库连接对象`Connection`后来操作`JDBC元数据`。 379 | 380 | 而`SpringBoot`方式则是直接使用项目中配置的`DataSource`对象实例来进行获取的`Connection`数据库连接对象后来操作`JDBC元数据`。 381 | > 注意:如果你是多数据源项目,默认会使用`primary`数据源实例。 382 | -------------------------------------------------------------------------------- /code-builder-core/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | code-builder 7 | com.gitee.hengboy 8 | 1.0.5.RELEASE 9 | 10 | 4.0.0 11 | code-builder-core 12 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/common/CodeBuilderProperties.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.common; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.common.enums.DbTypeEnum; 18 | import com.gitee.hengboy.builder.common.enums.EngineTypeEnum; 19 | import com.gitee.hengboy.builder.core.configuration.BuilderConfiguration; 20 | import lombok.Builder; 21 | import lombok.Data; 22 | 23 | import javax.sql.DataSource; 24 | import java.io.File; 25 | import java.util.List; 26 | 27 | /** 28 | * 代码生成器所属参数实体 29 | * 30 | * @author:于起宇 31 | * =============================== 32 | * Created with IDEA. 33 | * Date:2018/7/8 34 | * Time:4:58 PM 35 | * 简书:http://www.jianshu.com/u/092df3f77bca 36 | * ================================ 37 | */ 38 | @Data 39 | @Builder 40 | public class CodeBuilderProperties { 41 | private boolean execute; 42 | 43 | /** 44 | * maven-plugin形式所需参数 45 | * 数据库配置信息 46 | */ 47 | private String dbName; 48 | private String dbUserName; 49 | private String dbPassword; 50 | private String dbUrl; 51 | private String dbDriverClassName; 52 | /** 53 | * 数据源 54 | * spring-boot-starter形式直接配置 55 | */ 56 | private DataSource dataSource; 57 | 58 | private String ignoreClassPrefix; 59 | private List tables; 60 | private String generatorByPattern; 61 | private DbTypeEnum dbType; 62 | private EngineTypeEnum engineTypeEnum; 63 | private String projectBaseDir; 64 | private String builderDir; 65 | private String targetDir; 66 | private BuilderConfiguration builder; 67 | 68 | /** 69 | * 获取格式化后的数据库连接字符串 70 | * 71 | * @return 格式化后的数据库连接字符串 72 | */ 73 | public String getDbUrl() { 74 | return dbUrl + "/" + dbName; 75 | } 76 | 77 | /** 78 | * 根据不同系统类型格式化配置文件目录 79 | * 默认值未格式化前:classes.templates.builder 80 | * windows系统默认值格式化后:classes\templates\builder 81 | * osx/linux系统默认值格式化后:classes/templates/builder 82 | * 83 | * @return 格式化后的builder根路径 84 | */ 85 | public String getBuilderDir() { 86 | return builderDir.replace(".", File.separator); 87 | } 88 | 89 | /** 90 | * 根据不同系统类型格式化生成后目标文件目录 91 | * 默认值未格式化前:generated-sources.java 92 | * windows系统默认值格式化后:generated-sources\java 93 | * osx/linux系统默认值格式化后:generated-sources/java 94 | * 95 | * @return 格式化后的目录文件跟路径 96 | */ 97 | public String getTargetDir() { 98 | return targetDir.replace(".", File.separator); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/common/enums/DbTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.common.enums; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.core.database.DataBase; 18 | import com.gitee.hengboy.builder.core.database.impl.*; 19 | import lombok.Getter; 20 | 21 | /** 22 | * 数据库类型枚举 23 | * 24 | * @author:于起宇 25 | * =============================== 26 | * Created with IDEA. 27 | * Date:2018/7/8 28 | * Time:4:35 PM 29 | * 简书:http://www.jianshu.com/u/092df3f77bca 30 | * ================================ 31 | */ 32 | @Getter 33 | public enum DbTypeEnum { 34 | /** 35 | * MySQL数据库类型 36 | */ 37 | MySQL("com.mysql.jdbc.Driver", MySqlDataBase.class), 38 | /** 39 | * Db2数据库类型 40 | */ 41 | Db2("com.ibm.db2.jcc.DB2Driver", Db2DataBase.class), 42 | /** 43 | * PostgreSQL数据库类型 44 | */ 45 | PostgreSQL("org.postgresql.Driver", PostgreSqlDataBase.class), 46 | /** 47 | * SQLServer数据库类型 48 | */ 49 | SQLServer("com.microsoft.sqlserver.jdbc.SQLServerDriver", SqlServerDataBase.class), 50 | /** 51 | * Oracle数据库类型 52 | */ 53 | Oracle("oracle.jdbc.driver.OracleDriver", OracleDataBase.class); 54 | /** 55 | * 驱动类全限定名 56 | */ 57 | private String value; 58 | /** 59 | * 数据库实现类位置 60 | */ 61 | private Class dataBaseImplClass; 62 | 63 | DbTypeEnum(String value, Class dataBaseImplClass) { 64 | this.value = value; 65 | this.dataBaseImplClass = dataBaseImplClass; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/common/enums/EngineTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.common.enums; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.core.engine.EngineTemplate; 18 | import com.gitee.hengboy.builder.core.engine.impl.FreemarkerEngineImpl; 19 | import lombok.Getter; 20 | 21 | /** 22 | * 驱动类型枚举 23 | * 24 | * @author:于起宇 25 | * =============================== 26 | * Created with IDEA. 27 | * Date:2018/7/11 28 | * Time:5:54 PM 29 | * 简书:http://www.jianshu.com/u/092df3f77bca 30 | * ================================ 31 | */ 32 | @Getter 33 | public enum EngineTypeEnum { 34 | /** 35 | * freeMarker模板类型 36 | */ 37 | FREEMARKER("freemarker", FreemarkerEngineImpl.class); 38 | /** 39 | * 存放模板文件夹名称 40 | */ 41 | private String templateDirName; 42 | /** 43 | * 模板驱动实现类类型 44 | */ 45 | private Class implClass; 46 | 47 | EngineTypeEnum(String templateDirName, Class implClass) { 48 | this.templateDirName = templateDirName; 49 | this.implClass = implClass; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/common/enums/ErrorEnum.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.common.enums; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import lombok.Getter; 18 | 19 | /** 20 | * 错误信息枚举 21 | * 22 | * @author:于起宇 23 | * =============================== 24 | * Created with IDEA. 25 | * Date:2018/7/9 26 | * Time:2:35 PM 27 | * 简书:http://www.jianshu.com/u/092df3f77bca 28 | * ================================ 29 | */ 30 | @Getter 31 | public enum ErrorEnum { 32 | NOT_GET_TABLE("未获取到任何表."), 33 | NOT_GET_CONNECTION("无法获取数据库连接."), 34 | NOT_GET_COMMENT("无法获取表%s的备注信息."), 35 | NOT_GET_PRIMARY_KEYS("无法获取表%s内主键列表."), 36 | NOT_GET_COLUMN("无法获取表%s内的数据列列表"), 37 | NOT_ALLOW_DB_TYPE("不支持的数据库类型."), 38 | NOT_ALLOW_ENGINE("不支持的驱动模板类型."), 39 | NO_BUILDER_TABLE("请配置tables或者generatorByPattern参数后使用自动生成."); 40 | 41 | ErrorEnum(String message) { 42 | this.message = message; 43 | } 44 | 45 | private String message; 46 | } 47 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/common/enums/JavaTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.common.enums; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import lombok.Getter; 18 | 19 | /** 20 | * java类型装载转换枚举 21 | * 22 | * @author:于起宇 23 | * =============================== 24 | * Created with IDEA. 25 | * Date:2018/7/11 26 | * Time:3:43 PM 27 | * 简书:http://www.jianshu.com/u/092df3f77bca 28 | * ================================ 29 | */ 30 | @Getter 31 | public enum JavaTypeEnum { 32 | TYPE_BYTE("Byte", "java.lang.Byte"), 33 | TYPE_SHORT("Short", "java.lang.Short"), 34 | TYPE_INTEGER("Integer", "java.lang.Integer"), 35 | TYPE_LONG("Long", "java.lang.Long"), 36 | TYPE_FLOAT("Float", "java.lang.Float"), 37 | TYPE_DOUBLE("Double", "java.lang.Double"), 38 | TYPE_STRING("String", "java.lang.String"), 39 | TYPE_BOOLEAN("Boolean", "java.lang.Boolean"), 40 | TYPE_OBJECT("Object", "java.lang.Object"), 41 | TYPE_DATE("Date", "java.sql.Date"), 42 | TYPE_TIMESTAMP("Timestamp", "java.sql.Timestamp"), 43 | TYPE_BYTE_ARRAY("byte[]", "byte[]"), 44 | TYPE_BIG_DECIMAL("BigDecimal", "java.math.BigDecimal"); 45 | 46 | JavaTypeEnum(String shortName, String fullName) { 47 | this.shortName = shortName; 48 | this.fullName = fullName; 49 | } 50 | 51 | /** 52 | * 数据类型短名称 53 | * 如:String 54 | */ 55 | private String shortName; 56 | /** 57 | * 数据类型全名称 58 | * 如:java.lang.String 59 | */ 60 | private String fullName; 61 | } 62 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/common/enums/TableMetaDataEnum.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.common.enums; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import lombok.Getter; 18 | 19 | /** 20 | * 数据表元数据枚举 21 | * 22 | * @author:于起宇 23 | * =============================== 24 | * Created with IDEA. 25 | * Date:2018/7/9 26 | * Time:4:46 PM 27 | * 简书:http://www.jianshu.com/u/092df3f77bca 28 | * ================================ 29 | */ 30 | @Getter 31 | public enum TableMetaDataEnum { 32 | /** 33 | * 表类别(可为null) 34 | */ 35 | TABLE_CAT("TABLE_CAT"), 36 | /** 37 | * 表模式(可能为空),在oracle中获取的是命名空间 38 | */ 39 | TABLE_SCHEMA("TABLE_SCHEM"), 40 | /** 41 | * 表类型 42 | * 典型的类型是 "TABLE"、"VIEW"、"SYSTEM TABLE"、"GLOBAL TEMPORARY"、"LOCAL TEMPORARY"、"ALIAS" 和 "SYNONYM" 43 | */ 44 | TABLE_TYPE("TABLE_TYPE"), 45 | /** 46 | * 表名 47 | */ 48 | TABLE_NAME("TABLE_NAME"), 49 | /** 50 | * 列名 51 | */ 52 | COLUMN_NAME("COLUMN_NAME"), 53 | /** 54 | * 外键列表 55 | */ 56 | FK_COLUMN_NAME("FKCOLUMN_NAME"), 57 | /** 58 | * 列大小 59 | */ 60 | COLUMN_SIZE("COLUMN_SIZE"), 61 | /** 62 | * 是否为空 63 | */ 64 | NULLABLE("NULLABLE"), 65 | /** 66 | * 列默认值 67 | */ 68 | COLUMN_DEF("COLUMN_DEF"), 69 | /** 70 | * 列是否自增 71 | */ 72 | IS_AUTOINCREMENT("IS_AUTOINCREMENT"), 73 | /** 74 | * 列数据类型 75 | */ 76 | DATA_TYPE("DATA_TYPE"), 77 | /** 78 | * 列备注信息 79 | */ 80 | REMARKS("REMARKS"), 81 | /** 82 | * 小数位数。对于DECIMAL_DIGITS不适用的数据类型,将返回Null。 83 | */ 84 | DECIMAL_DIGITS("DECIMAL_DIGITS"), 85 | /** 86 | * 表中列的索引(从1开始) 87 | */ 88 | ORDINAL_POSITION("ORDINAL_POSITION"); 89 | 90 | private String value; 91 | 92 | TableMetaDataEnum(String value) { 93 | this.value = value; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/common/exception/CodeBuilderException.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.common.exception; 2 | 3 | import com.gitee.hengboy.builder.common.enums.ErrorEnum; 4 | 5 | /** 6 | * 代码生成异常定义 7 | * 8 | * @author:于起宇 9 | * =============================== 10 | * Created with IDEA. 11 | * Date:2018/7/17 12 | * Time:11:33 AM 13 | * 简书:http://www.jianshu.com/u/092df3f77bca 14 | * ================================ 15 | */ 16 | public class CodeBuilderException extends RuntimeException { 17 | /** 18 | * 初始化代码异常 19 | * 20 | * @param errorEnum 错误枚举 21 | * @param params 枚举内字符串参数占位数组 22 | */ 23 | public CodeBuilderException(ErrorEnum errorEnum, String... params) { 24 | super(String.format(errorEnum.getMessage(), params)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/common/util/StringUtil.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 恒宇少年 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.gitee.hengboy.builder.common.util; 17 | 18 | /** 19 | * 字符串工具类 20 | * 21 | * @author:于起宇 22 | * =============================== 23 | * Created with IDEA. 24 | * Date:2018/7/8 25 | * Time:5:30 PM 26 | * 简书:http://www.jianshu.com/u/092df3f77bca 27 | * ================================ 28 | */ 29 | public class StringUtil { 30 | /** 31 | * 验证对象是否为空 32 | * 33 | * @param object 对象实例 34 | * @return true:不为空,false:为空 35 | */ 36 | public static boolean isNotEmpty(Object object) { 37 | if (object instanceof String) { 38 | return object != null && String.valueOf(object).length() > 0; 39 | } 40 | return object != null; 41 | } 42 | 43 | /** 44 | * 转换unicode字符集 45 | * 46 | * @param s 包含unicode的字符串 47 | * @return 格式化后的字符串 48 | */ 49 | public static String toUnicodeString(String s) { 50 | StringBuilder sb = new StringBuilder(); 51 | for (int i = 0; i < s.length(); i++) { 52 | char c = s.charAt(i); 53 | if (c >= 0 && c <= 255) { 54 | sb.append(c); 55 | } else { 56 | sb.append("\\u" + Integer.toHexString(c)); 57 | } 58 | } 59 | return sb.toString(); 60 | } 61 | 62 | /** 63 | * 格式化驼峰命名字符串 64 | * 65 | * @param inputString 未格式化的字符串 66 | * @param firstCharacterUppercase 首字母是否大写 67 | * @return 格式化后的字符串 68 | */ 69 | public static String getCamelCaseString(String inputString, boolean firstCharacterUppercase) { 70 | StringBuilder sb = new StringBuilder(); 71 | 72 | boolean nextUpperCase = false; 73 | for (int i = 0; i < inputString.length(); i++) { 74 | char c = inputString.charAt(i); 75 | 76 | switch (c) { 77 | case '_': 78 | case '-': 79 | case '@': 80 | case '$': 81 | case '#': 82 | case ' ': 83 | case '/': 84 | case '&': 85 | if (sb.length() > 0) { 86 | nextUpperCase = true; 87 | } 88 | break; 89 | 90 | default: 91 | if (nextUpperCase) { 92 | sb.append(Character.toUpperCase(c)); 93 | nextUpperCase = false; 94 | } else { 95 | sb.append(Character.toLowerCase(c)); 96 | } 97 | break; 98 | } 99 | } 100 | 101 | if (firstCharacterUppercase) { 102 | sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); 103 | } 104 | 105 | return sb.toString(); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/configuration/BuilderConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.configuration; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.common.util.StringUtil; 18 | import lombok.Data; 19 | 20 | import java.io.File; 21 | import java.util.List; 22 | 23 | /** 24 | * 代码生成配置 25 | * 26 | * @author:于起宇 =============================== 27 | * Created with IDEA. 28 | * Date:2018/7/12 29 | * Time:4:44 PM 30 | * 简书:http://www.jianshu.com/u/092df3f77bca 31 | * ================================ 32 | */ 33 | @Data 34 | public class BuilderConfiguration { 35 | /** 36 | * 模板配置列表 37 | */ 38 | private List templates; 39 | /** 40 | * package包名前缀 41 | */ 42 | private String packagePrefix; 43 | 44 | /** 45 | * 获取不同系统的package转换目录分割后的路径 46 | * 47 | * @return 获取不同系统格式化后的包名路径 48 | */ 49 | public String getDiffSysPackagePrefix() { 50 | if (!StringUtil.isNotEmpty(packagePrefix)) { 51 | return packagePrefix; 52 | } 53 | return packagePrefix.replace(".", File.separator); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/configuration/TemplateConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.configuration; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import lombok.Data; 19 | 20 | /** 21 | * 模板配置基本信息 22 | * 23 | * @author:于起宇 24 | * =============================== 25 | * Created with IDEA. 26 | * Date:2018/7/12 27 | * Time:4:45 PM 28 | * 简书:http://www.jianshu.com/u/092df3f77bca 29 | * ================================ 30 | */ 31 | @Data 32 | public class TemplateConfiguration { 33 | /** 34 | * 模板名称 35 | * 如:model.ftl 36 | */ 37 | private String name; 38 | /** 39 | * 包名 40 | */ 41 | private String packageName; 42 | /** 43 | * 生成文件的前缀名 44 | * 如:DXxx,D则是前缀 45 | */ 46 | private String filePrefix; 47 | /** 48 | * 生成文件的后缀名 49 | */ 50 | private String fileSuffix; 51 | } 52 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/AbstractDataBase.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 19 | import com.gitee.hengboy.builder.common.enums.ErrorEnum; 20 | import com.gitee.hengboy.builder.common.enums.TableMetaDataEnum; 21 | import com.gitee.hengboy.builder.common.exception.CodeBuilderException; 22 | import com.gitee.hengboy.builder.common.util.StringUtil; 23 | import com.gitee.hengboy.builder.core.database.model.Column; 24 | import com.gitee.hengboy.builder.core.database.model.Table; 25 | import com.gitee.hengboy.builder.core.database.model.util.JavaTypeResolver; 26 | import com.gitee.hengboy.builder.core.database.model.util.JdbcTypeResolver; 27 | 28 | import java.sql.*; 29 | import java.util.ArrayList; 30 | import java.util.List; 31 | 32 | /** 33 | * 抽象数据库实例类 34 | * 35 | * @author:于起宇 =============================== 36 | * Created with IDEA. 37 | * Date:2018/7/8 38 | * Time:5:24 PM 39 | * 简书:http://www.jianshu.com/u/092df3f77bca 40 | * ================================ 41 | */ 42 | public abstract class AbstractDataBase implements DataBase { 43 | /** 44 | * 数据库连接对象 45 | */ 46 | protected Connection connection; 47 | /** 48 | * 代码生成器参数配置实例 49 | */ 50 | protected CodeBuilderProperties codeBuilderProperties; 51 | 52 | /** 53 | * 构造函数传递参数配置实例 54 | * 55 | * @param codeBuilderProperties 生成所需参数对象 56 | */ 57 | public AbstractDataBase(CodeBuilderProperties codeBuilderProperties) { 58 | this.codeBuilderProperties = codeBuilderProperties; 59 | // 获取数据库连接 60 | getConnection(); 61 | } 62 | 63 | /** 64 | * 获取数据库连接对象 65 | * 66 | * @return 数据库连接对象 67 | */ 68 | public Connection getConnection() { 69 | try { 70 | /* 71 | * 连接不存在 || 连接失效 72 | * 重新获取连接 73 | */ 74 | if (connection == null || connection.isClosed()) { 75 | // spring-boot-starter方式获取数据库连接 76 | if (codeBuilderProperties.getDataSource() != null) { 77 | connection = codeBuilderProperties.getDataSource().getConnection(); 78 | } 79 | // maven-plugin插件形式获取数据库连接 80 | else { 81 | // 默认使用数据库驱动类型内的限定类名 82 | String driverClassName = codeBuilderProperties.getDbType().getValue(); 83 | // 存在自定义的驱动限定类名时使用自定义来实例化驱动对象 84 | if (StringUtil.isNotEmpty(codeBuilderProperties.getDbDriverClassName())) { 85 | driverClassName = codeBuilderProperties.getDbDriverClassName(); 86 | } 87 | //加载驱动程序 88 | Class.forName(driverClassName); 89 | // 获取数据库连接 90 | connection = DriverManager.getConnection(codeBuilderProperties.getDbUrl(), codeBuilderProperties.getDbUserName(), codeBuilderProperties.getDbPassword()); 91 | } 92 | } 93 | return connection; 94 | } catch (Exception e) { 95 | e.printStackTrace(); 96 | } 97 | throw new CodeBuilderException(ErrorEnum.NOT_GET_CONNECTION); 98 | } 99 | 100 | /** 101 | * 关闭数据库连接对象 102 | */ 103 | public void closeConnection() { 104 | try { 105 | if (!connection.isClosed()) { 106 | connection.close(); 107 | } 108 | } catch (SQLException e) { 109 | e.printStackTrace(); 110 | } 111 | } 112 | 113 | /** 114 | * 获取表名列表 115 | * 116 | * @param tableNamePattern 表名表达式 117 | * @return 表名列表 118 | */ 119 | public List getTableNames(String tableNamePattern) { 120 | try { 121 | // 获取该数据库内的所有表 122 | ResultSet resultSet = connection.getMetaData().getTables(connection.getCatalog(), codeBuilderProperties.getDbUserName(), tableNamePattern, new String[]{"TABLE"}); 123 | List tables = new ArrayList(); 124 | while (resultSet.next()) { 125 | // 获取表名 126 | String tableName = resultSet.getString(TableMetaDataEnum.TABLE_NAME.getValue()); 127 | // 获取表格基本信息 128 | tables.add(tableName); 129 | } 130 | return tables; 131 | } catch (Exception e) { 132 | e.printStackTrace(); 133 | } 134 | throw new CodeBuilderException(ErrorEnum.NOT_GET_TABLE); 135 | } 136 | 137 | /** 138 | * 获取数据库内的所有表 139 | * 140 | * @param tableNamePattern 表名表达式 141 | * @return 数据表列表结果集 142 | */ 143 | public List getTables(String tableNamePattern) { 144 | try { 145 | // 获取该数据库内的所有表 146 | ResultSet resultSet = connection.getMetaData().getTables(connection.getCatalog(), codeBuilderProperties.getDbUserName(), tableNamePattern, new String[]{"TABLE"}); 147 | List
tables = new ArrayList
(); 148 | while (resultSet.next()) { 149 | // 获取表名 150 | String tableName = resultSet.getString(TableMetaDataEnum.TABLE_NAME.getValue()); 151 | // 获取表格基本信息 152 | tables.add(getTable(tableName)); 153 | } 154 | return tables; 155 | } catch (Exception e) { 156 | e.printStackTrace(); 157 | } 158 | throw new CodeBuilderException(ErrorEnum.NOT_GET_TABLE); 159 | } 160 | 161 | /** 162 | * 获取数据表基本信息 163 | * 164 | * @param tableName 表名 165 | * @return 数据表对象实例 166 | */ 167 | public Table getTable(String tableName) { 168 | // 构建数据表对象 169 | Table.TableBuilder tableBuilder = Table.builder(); 170 | try { 171 | ResultSet resultSet = getConnection().getMetaData().getTables(null, null, tableName, new String[]{"TABLE"}); 172 | if (resultSet.next()) { 173 | tableBuilder 174 | // 表名 175 | .tableName(tableName) 176 | // 实体类名称 177 | .entityName(StringUtil.getCamelCaseString(tableName, true)) 178 | // 表类别 179 | .catalog(resultSet.getString(TableMetaDataEnum.TABLE_CAT.getValue())) 180 | // 表模式 181 | .schema(resultSet.getString(TableMetaDataEnum.TABLE_SCHEMA.getValue())) 182 | // 表类型 183 | .tableType(resultSet.getString(TableMetaDataEnum.TABLE_TYPE.getValue())) 184 | // 获取备注信息 185 | .remark(getTableComment(tableName)) 186 | // 所有列,排除主键 187 | .columns(getColumns(tableName)) 188 | // 主键列表 189 | .primaryKeys(getPrimaryKeys(tableName)); 190 | } 191 | } catch (SQLException e) { 192 | e.printStackTrace(); 193 | } 194 | return tableBuilder.build().buildAfterSetting(codeBuilderProperties); 195 | } 196 | 197 | /** 198 | * 根据结果集获取列的详细信息 199 | * 根据不同的columnPattern获取到的列元数据 200 | * 201 | * @param resultSet 结果集 202 | * @param isPrimaryColumn true:主键列,false:普通列 203 | * @return 列基本信息对象 204 | */ 205 | private Column getColumn(ResultSet resultSet, boolean isPrimaryColumn) { 206 | try { 207 | // 数据库字段类型 208 | int jdbcType = resultSet.getInt(TableMetaDataEnum.DATA_TYPE.getValue()); 209 | // 列名 210 | String columnName = resultSet.getString(TableMetaDataEnum.COLUMN_NAME.getValue()); 211 | // 表名 212 | String tableName = resultSet.getString(TableMetaDataEnum.TABLE_NAME.getValue()); 213 | 214 | return Column.builder() 215 | // 列名 216 | .columnName(columnName) 217 | // 列长度 218 | .size(resultSet.getInt(TableMetaDataEnum.COLUMN_SIZE.getValue())) 219 | // 是否为空 220 | .nullable(resultSet.getBoolean(TableMetaDataEnum.NULLABLE.getValue())) 221 | // 默认值 222 | .defaultValue(resultSet.getString(TableMetaDataEnum.COLUMN_DEF.getValue())) 223 | // 数据库列类型 224 | .jdbcType(jdbcType) 225 | // 是否自增 226 | .autoincrement(hasColumn(resultSet, TableMetaDataEnum.IS_AUTOINCREMENT.getValue()) ? resultSet.getBoolean(TableMetaDataEnum.IS_AUTOINCREMENT.getValue()) : false) 227 | // 列备注信息 228 | .remark(resultSet.getString(TableMetaDataEnum.REMARKS.getValue())) 229 | // 精度 230 | .decimalDigits(resultSet.getInt(TableMetaDataEnum.DECIMAL_DIGITS.getValue())) 231 | // jdbc类型名称 232 | .jdbcTypeName(JdbcTypeResolver.getJdbcTypeName(jdbcType)) 233 | // 格式化后的java field 234 | .javaProperty(StringUtil.getCamelCaseString(columnName, false)) 235 | // 对应的java数据类型 236 | .javaType(JavaTypeResolver.getJavaType(jdbcType, false)) 237 | // java数据类型 238 | .fullJavaType(JavaTypeResolver.getJavaType(jdbcType, true)) 239 | // 是否为主键列 240 | // 如果是主键获取列信息,直接返回true 241 | .primaryKey(!isPrimaryColumn ? isPrimaryKey(tableName, columnName) : isPrimaryColumn) 242 | // 是否为外键列 243 | // 如果是主键获取列信息,直接返回false 244 | .foreignKey(!isPrimaryColumn ? isForeignKey(tableName, columnName) : false) 245 | .build(); 246 | } catch (SQLException e) { 247 | e.printStackTrace(); 248 | } 249 | return null; 250 | } 251 | 252 | /** 253 | * 获取表内的所有列 254 | * 255 | * @param tableName 表名 256 | * @return 数据列列表 257 | */ 258 | public List getColumns(String tableName) { 259 | List columns = new ArrayList(); 260 | try { 261 | // 获取列信息 262 | ResultSet resultSet = getConnection().getMetaData().getColumns(null, null, tableName, "%"); 263 | while (resultSet.next()) { 264 | columns.add(getColumn(resultSet, false)); 265 | } 266 | return columns; 267 | } catch (SQLException e) { 268 | e.printStackTrace(); 269 | } 270 | throw new CodeBuilderException(ErrorEnum.NOT_GET_COLUMN, tableName); 271 | } 272 | 273 | /** 274 | * 验证指定的字段是否为主键 275 | * 276 | * @param tableName 表名 277 | * @param columnName 列名 278 | * @return 是否为主键,true:主键,false:非主键 279 | */ 280 | public boolean isPrimaryKey(String tableName, String columnName) { 281 | try { 282 | // 获取表内的主键列表 283 | ResultSet resultSet = connection.getMetaData().getPrimaryKeys(null, null, tableName); 284 | while (resultSet.next()) { 285 | // 获取主键的列名 286 | String pkColumnName = resultSet.getString(TableMetaDataEnum.COLUMN_NAME.getValue()); 287 | if (columnName.equals(pkColumnName)) { 288 | return true; 289 | } 290 | } 291 | } catch (SQLException e) { 292 | e.printStackTrace(); 293 | } 294 | return false; 295 | } 296 | 297 | /** 298 | * 验证指定列是否为外键 299 | * 300 | * @param tableName 表名 301 | * @param columnName 列名 302 | * @return 是否为外键,true:外键,false:非外键 303 | */ 304 | public boolean isForeignKey(String tableName, String columnName) { 305 | try { 306 | // 获取表内的外键列表 307 | ResultSet resultSet = connection.getMetaData().getImportedKeys(null, null, tableName); 308 | while (resultSet.next()) { 309 | // 获取外键的列名 310 | String fkColumnName = resultSet.getString(TableMetaDataEnum.FK_COLUMN_NAME.getValue()); 311 | if (columnName.equals(fkColumnName)) { 312 | return true; 313 | } 314 | } 315 | } catch (SQLException e) { 316 | e.printStackTrace(); 317 | } 318 | return false; 319 | } 320 | 321 | /** 322 | * 获取表内的主键列表 323 | * 324 | * @param tableName 表名 325 | * @return 主键列表 326 | */ 327 | public List getPrimaryKeys(String tableName) { 328 | try { 329 | // 获取表内的主键列表 330 | ResultSet resultSet = connection.getMetaData().getPrimaryKeys(null, null, tableName); 331 | List primaryKeys = new ArrayList(); 332 | while (resultSet.next()) { 333 | // 获取主键的列名 334 | String columnName = resultSet.getString(TableMetaDataEnum.COLUMN_NAME.getValue()); 335 | // 获取主键列的详细信息 336 | ResultSet columnResultSet = connection.getMetaData().getColumns(null, null, tableName, columnName); 337 | if (columnResultSet.next()) { 338 | // 添加主键信息 339 | primaryKeys.add(getColumn(columnResultSet, true)); 340 | } 341 | } 342 | return primaryKeys; 343 | } catch (SQLException e) { 344 | e.printStackTrace(); 345 | } 346 | throw new CodeBuilderException(ErrorEnum.NOT_GET_PRIMARY_KEYS, tableName); 347 | } 348 | 349 | /** 350 | * 结果集内是否存在自增的列 351 | * 352 | * @param rs 结果集 353 | * @param columnName 自增列名 354 | * @return true:存在列表,false:不存在列 355 | * @throws SQLException 数据库异常 356 | */ 357 | private boolean hasColumn(ResultSet rs, String columnName) throws SQLException { 358 | ResultSetMetaData resultSetMetaData = rs.getMetaData(); 359 | int columns = resultSetMetaData.getColumnCount(); 360 | for (int x = 1; x <= columns; x++) { 361 | if (columnName.equals(resultSetMetaData.getColumnName(x))) { 362 | return true; 363 | } 364 | } 365 | return false; 366 | } 367 | } 368 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/DataBase.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.core.database.model.Column; 18 | import com.gitee.hengboy.builder.core.database.model.Table; 19 | 20 | import java.sql.Connection; 21 | import java.util.List; 22 | 23 | /** 24 | * 数据库实例接口 25 | * 26 | * @author:于起宇 =============================== 27 | * Created with IDEA. 28 | * Date:2018/7/8 29 | * Time:5:23 PM 30 | * 简书:http://www.jianshu.com/u/092df3f77bca 31 | * ================================ 32 | */ 33 | public interface DataBase { 34 | /** 35 | * 获取数据库的连接 36 | * 37 | * @return 数据库连接对象 38 | */ 39 | Connection getConnection(); 40 | 41 | /** 42 | * 关闭数据库连接 43 | */ 44 | void closeConnection(); 45 | 46 | /** 47 | * 获取数据库内的所有数据表 48 | * 49 | * @param tableNamePattern 表名称表达式过滤,如:sys_%,则仅仅查询出【sys_】开头的所有表 50 | * @return 数据表列表 51 | */ 52 | List
getTables(String tableNamePattern); 53 | 54 | /** 55 | * 获取表名称列表 56 | * 57 | * @param tableNamePattern 获取表名时使用的表达式 58 | * @return 表名列表 59 | */ 60 | List getTableNames(String tableNamePattern); 61 | 62 | /** 63 | * 根据表名获取数据表对象 64 | * 65 | * @param tableName 表名 66 | * @return 表对象实例 67 | */ 68 | Table getTable(String tableName); 69 | 70 | /** 71 | * 查询表内的全部列表 72 | * 73 | * @param tableName 表名 74 | * @return 数据列列表 75 | */ 76 | List getColumns(String tableName); 77 | 78 | /** 79 | * 查询表内 80 | * 81 | * @param tableName 表名 82 | * @return 主键列表 83 | */ 84 | List getPrimaryKeys(String tableName); 85 | 86 | /** 87 | * 是否为主键列 88 | * 89 | * @param tableName 表名 90 | * @param columnName 列名 91 | * @return 是否为主键,true:主键,false:非主键 92 | */ 93 | boolean isPrimaryKey(String tableName, String columnName); 94 | 95 | /** 96 | * 是否为外键 97 | * 98 | * @param tableName 表名 99 | * @param columnName 列名 100 | * @return 是否外键,true:外键,false:非外键 101 | */ 102 | boolean isForeignKey(String tableName, String columnName); 103 | 104 | /** 105 | * 获取表备注信息 106 | * 107 | * @param tableName 表名 108 | * @return 表备注信息 109 | */ 110 | String getTableComment(String tableName); 111 | } 112 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/DataBaseFactory.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 19 | import com.gitee.hengboy.builder.common.enums.DbTypeEnum; 20 | import com.gitee.hengboy.builder.common.enums.ErrorEnum; 21 | import com.gitee.hengboy.builder.common.exception.CodeBuilderException; 22 | 23 | import java.lang.reflect.Constructor; 24 | 25 | /** 26 | * 数据库工厂 27 | * 28 | * @author:于起宇 =============================== 29 | * Created with IDEA. 30 | * Date:2018/7/8 31 | * Time:5:22 PM 32 | * 简书:http://www.jianshu.com/u/092df3f77bca 33 | * ================================ 34 | */ 35 | public class DataBaseFactory { 36 | /** 37 | * 构造函数私有化 38 | * 禁止通过new方式实例化对象 39 | */ 40 | private DataBaseFactory() { 41 | } 42 | 43 | /** 44 | * 获取配置的数据库类型实例 45 | * 46 | * @param codeBuilderProperties 配置构建参数实体 47 | * @return 数据库实例 48 | */ 49 | public static DataBase newInstance(CodeBuilderProperties codeBuilderProperties) { 50 | // 数据库类型枚举实例 51 | DbTypeEnum dbTypeEnum = codeBuilderProperties.getDbType(); 52 | try { 53 | // 获取数据库实现类的构造函数 54 | Constructor constructor = dbTypeEnum.getDataBaseImplClass().getConstructor(CodeBuilderProperties.class); 55 | // 反射获取数据库实现类实例 56 | return (DataBase) constructor.newInstance(codeBuilderProperties); 57 | } catch (Exception e) { 58 | e.printStackTrace(); 59 | throw new CodeBuilderException(ErrorEnum.NOT_ALLOW_DB_TYPE); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/impl/Db2DataBase.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database.impl; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 18 | import com.gitee.hengboy.builder.core.database.AbstractDataBase; 19 | 20 | /** 21 | * DB2数据库实现 22 | * @author:于起宇 23 | * =============================== 24 | * Created with IDEA. 25 | * Date:2018/7/9 26 | * Time:11:38 AM 27 | * 简书:http://www.jianshu.com/u/092df3f77bca 28 | * ================================ 29 | */ 30 | public class Db2DataBase extends AbstractDataBase { 31 | 32 | public Db2DataBase(CodeBuilderProperties codeBuilderProperties) { 33 | super(codeBuilderProperties); 34 | } 35 | 36 | public String getTableComment(String tableName){ 37 | // TODO 暂未支持 38 | return null; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/impl/MySqlDataBase.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database.impl; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 18 | import com.gitee.hengboy.builder.common.enums.ErrorEnum; 19 | import com.gitee.hengboy.builder.common.exception.CodeBuilderException; 20 | import com.gitee.hengboy.builder.core.database.AbstractDataBase; 21 | 22 | import java.sql.PreparedStatement; 23 | import java.sql.ResultSet; 24 | import java.sql.SQLException; 25 | 26 | /** 27 | * MySQL数据库类型实体 28 | * 29 | * @author:于起宇 30 | * =============================== 31 | * Created with IDEA. 32 | * Date:2018/7/8 33 | * Time:5:24 PM 34 | * 简书:http://www.jianshu.com/u/092df3f77bca 35 | * ================================ 36 | */ 37 | public class MySqlDataBase extends AbstractDataBase { 38 | /** 39 | * MySQL查询表状态的执行SQL 40 | */ 41 | private static final String TABLE_COMMENT_SQL = "show table status where NAME=?"; 42 | /** 43 | * 表备注字段名称 44 | */ 45 | private static final String TABLE_COMMENT_COLUMN = "COMMENT"; 46 | 47 | public MySqlDataBase(CodeBuilderProperties codeBuilderProperties) { 48 | super(codeBuilderProperties); 49 | } 50 | 51 | /** 52 | * 获取表备注信息 53 | * 54 | * @param tableName 表名 55 | * @return 表备注信息 56 | */ 57 | public String getTableComment(String tableName) { 58 | try { 59 | PreparedStatement statement = connection.prepareStatement(TABLE_COMMENT_SQL); 60 | statement.setString(1, tableName); 61 | ResultSet resultSet = statement.executeQuery(); 62 | if (resultSet.next()) { 63 | return resultSet.getString(TABLE_COMMENT_COLUMN); 64 | } 65 | resultSet.close(); 66 | statement.close(); 67 | } catch (SQLException e) { 68 | e.printStackTrace(); 69 | } 70 | throw new CodeBuilderException(ErrorEnum.NOT_GET_COMMENT, tableName); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/impl/OracleDataBase.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database.impl; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 18 | import com.gitee.hengboy.builder.core.database.AbstractDataBase; 19 | 20 | /** 21 | * Oracle数据库实现 22 | * 23 | * @author:于起宇 24 | * =============================== 25 | * Created with IDEA. 26 | * Date:2018/7/9 27 | * Time:11:41 AM 28 | * 简书:http://www.jianshu.com/u/092df3f77bca 29 | * ================================ 30 | */ 31 | public class OracleDataBase extends AbstractDataBase { 32 | 33 | public OracleDataBase(CodeBuilderProperties codeBuilderProperties) { 34 | super(codeBuilderProperties); 35 | } 36 | 37 | /** 38 | * 获取表的备注信息 39 | * 40 | * @param tableName 表名 41 | * @return 表备注信息 42 | */ 43 | public String getTableComment(String tableName) { 44 | // TODO 暂未支持 45 | return null; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/impl/PostgreSqlDataBase.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database.impl; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 18 | import com.gitee.hengboy.builder.core.database.AbstractDataBase; 19 | 20 | /** 21 | * Postgresql 数据库 22 | * 23 | * @author:于起宇 24 | * =============================== 25 | * Created with IDEA. 26 | * Date:2018/7/9 27 | * Time:11:40 AM 28 | * 简书:http://www.jianshu.com/u/092df3f77bca 29 | * ================================ 30 | */ 31 | public class PostgreSqlDataBase extends AbstractDataBase { 32 | 33 | public PostgreSqlDataBase(CodeBuilderProperties codeBuilderProperties) { 34 | super(codeBuilderProperties); 35 | } 36 | 37 | 38 | public String getTableComment(String tableName) { 39 | // TODO 暂未支持 40 | return null; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/impl/SqlServerDataBase.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database.impl; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 18 | import com.gitee.hengboy.builder.core.database.AbstractDataBase; 19 | 20 | /** 21 | * SqlServer数据库实现 22 | * @author:于起宇 23 | * =============================== 24 | * Created with IDEA. 25 | * Date:2018/7/9 26 | * Time:11:41 AM 27 | * 简书:http://www.jianshu.com/u/092df3f77bca 28 | * ================================ 29 | */ 30 | public class SqlServerDataBase extends AbstractDataBase { 31 | public SqlServerDataBase(CodeBuilderProperties codeBuilderProperties) { 32 | super(codeBuilderProperties); 33 | } 34 | 35 | 36 | public String getTableComment(String tableName){ 37 | // TODO 暂未支持 38 | return null; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/model/Column.java: -------------------------------------------------------------------------------- 1 | 2 | package com.gitee.hengboy.builder.core.database.model; 3 | 4 | /** 5 | * Copyright 2018 恒宇少年 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | import lombok.Builder; 20 | import lombok.Getter; 21 | import lombok.Setter; 22 | 23 | /** 24 | * 数据表内的列对象 25 | * 26 | * @author:于起宇 27 | * =============================== 28 | * Created with IDEA. 29 | * Date:2018/7/8 30 | * Time:5:44 PM 31 | * 简书:http://www.jianshu.com/u/092df3f77bca 32 | * ================================ 33 | */ 34 | @Getter 35 | @Setter 36 | @Builder 37 | public class Column { 38 | /** 39 | * 列名 40 | */ 41 | private String columnName; 42 | /** 43 | * 是否为主键 44 | */ 45 | private boolean primaryKey; 46 | /** 47 | * 是否为外键 48 | */ 49 | private boolean foreignKey; 50 | /** 51 | * 列长度 52 | */ 53 | private int size; 54 | /** 55 | * 小数点位数 56 | */ 57 | private int decimalDigits; 58 | /** 59 | * 是否为空 60 | */ 61 | private boolean nullable; 62 | /** 63 | * 是否自增 64 | */ 65 | private boolean autoincrement; 66 | /** 67 | * 默认值 68 | */ 69 | private String defaultValue; 70 | /** 71 | * 备注信息 72 | */ 73 | private String remark; 74 | /** 75 | * 数据库类型 76 | */ 77 | private int jdbcType; 78 | /** 79 | * java.sql.Types对应的类型名称 80 | */ 81 | private String jdbcTypeName; 82 | /** 83 | * 列名格式化后对应实体类内的属性 84 | */ 85 | private String javaProperty; 86 | /** 87 | * java.lang.xxx数据类型 88 | */ 89 | private String javaType; 90 | /** 91 | * java.lang.xxx数据类型全名称 92 | */ 93 | private String fullJavaType; 94 | } 95 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/model/Key.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database.model; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import lombok.Builder; 18 | import lombok.Data; 19 | 20 | /** 21 | * 数据表内的主键、外键对象 22 | * 23 | * @author:于起宇 24 | * =============================== 25 | * Created with IDEA. 26 | * Date:2018/7/8 27 | * Time:5:32 PM 28 | * 简书:http://www.jianshu.com/u/092df3f77bca 29 | * ================================ 30 | */ 31 | @Data 32 | @Builder 33 | public class Key { 34 | /** 35 | * 主键表名 36 | */ 37 | private String pkTableName; 38 | /** 39 | * 主键列名 40 | */ 41 | private String pkColumnName; 42 | /** 43 | * 外键表名 44 | */ 45 | private String fkTableName; 46 | /** 47 | * 外键列名 48 | */ 49 | private String fkColumnName; 50 | /** 51 | * 外键中的序列号(值1表示外键的第一列,值2表示外键中的第二列)。 52 | */ 53 | private Integer seq; 54 | 55 | } 56 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/model/Table.java: -------------------------------------------------------------------------------- 1 | 2 | package com.gitee.hengboy.builder.core.database.model; 3 | 4 | /** 5 | * Copyright 2018 恒宇少年 6 | *

7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | *

11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | *

13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 21 | import com.gitee.hengboy.builder.common.enums.JavaTypeEnum; 22 | import com.gitee.hengboy.builder.common.util.StringUtil; 23 | import lombok.Builder; 24 | import lombok.Data; 25 | 26 | import java.util.List; 27 | 28 | /** 29 | * 数据表对象 30 | * 31 | * @author:于起宇 =============================== 32 | * Created with IDEA. 33 | * Date:2018/7/8 34 | * Time:5:28 PM 35 | * 简书:http://www.jianshu.com/u/092df3f77bca 36 | * ================================ 37 | */ 38 | @Builder 39 | @Data 40 | public class Table { 41 | /** 42 | * 表名 43 | */ 44 | private String tableName; 45 | /** 46 | * 表驼峰名称 47 | */ 48 | private String tableCamelName; 49 | /** 50 | * 表类型 51 | */ 52 | private String tableType; 53 | /** 54 | * 表别名 55 | */ 56 | private String tableAlias; 57 | /** 58 | * 表备注信息 59 | */ 60 | private String remark; 61 | /** 62 | * 实体名称 63 | */ 64 | private String entityName; 65 | /** 66 | * catalog 67 | */ 68 | private String catalog; 69 | /** 70 | * schema 71 | */ 72 | private String schema; 73 | /** 74 | * 数据列列表 75 | */ 76 | private List columns; 77 | /** 78 | * 主键列表 79 | */ 80 | private List primaryKeys; 81 | /** 82 | * 是否存在java.sql.Date类型的列 83 | */ 84 | private boolean hasSqlDate; 85 | /** 86 | * 是否存在TimeStamp的列 87 | */ 88 | private boolean hasTimeStamp; 89 | /** 90 | * 是否存在BigDecimal的列 91 | */ 92 | private boolean hasBigDecimal; 93 | 94 | /** 95 | * 构建对象后设置是否存在特殊类型的字段 96 | * 如:java.math.BigDecimal、java.sql.TimeStamp等 97 | * 98 | * @param codeBuilderProperties 参数对象 99 | * @return Table实例 100 | */ 101 | public Table buildAfterSetting(CodeBuilderProperties codeBuilderProperties) { 102 | for (Column column : columns) { 103 | // 是否存在bigDecimal的列 104 | if (JavaTypeEnum.TYPE_BIG_DECIMAL.getFullName().equals(column.getFullJavaType())) { 105 | this.hasBigDecimal = true; 106 | } 107 | // 是否存在timeStamp的列 108 | if (JavaTypeEnum.TYPE_TIMESTAMP.getFullName().equals(column.getFullJavaType())) { 109 | this.hasTimeStamp = true; 110 | } 111 | // 是否存在java.sql.Date的列 112 | if (JavaTypeEnum.TYPE_DATE.getFullName().equals(column.getFullJavaType())) { 113 | this.hasSqlDate = true; 114 | } 115 | } 116 | // 自动忽略前缀 117 | if (StringUtil.isNotEmpty(codeBuilderProperties.getIgnoreClassPrefix())) { 118 | entityName = entityName.replaceFirst(codeBuilderProperties.getIgnoreClassPrefix(), ""); 119 | } 120 | return this; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/model/util/JavaTypeResolver.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.database.model.util; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.common.enums.JavaTypeEnum; 18 | 19 | import java.sql.Types; 20 | import java.util.HashMap; 21 | import java.util.Map; 22 | 23 | /** 24 | * Java数据类型装载器 25 | * 26 | * @author:于起宇 =============================== 27 | * Created with IDEA. 28 | * Date:2018/7/8 29 | * Time:6:13 PM 30 | * 简书:http://www.jianshu.com/u/092df3f77bca 31 | * ================================ 32 | */ 33 | public class JavaTypeResolver { 34 | 35 | /** 36 | * java 字段类型映射集合 37 | */ 38 | private static Map typeMap; 39 | 40 | 41 | static { 42 | typeMap = new HashMap(); 43 | typeMap.put(Types.ARRAY, JavaTypeEnum.TYPE_OBJECT); 44 | typeMap.put(Types.BIGINT, JavaTypeEnum.TYPE_LONG); 45 | typeMap.put(Types.BINARY, JavaTypeEnum.TYPE_BYTE_ARRAY); 46 | typeMap.put(Types.BIT, JavaTypeEnum.TYPE_BOOLEAN); 47 | typeMap.put(Types.BLOB, JavaTypeEnum.TYPE_BYTE_ARRAY); 48 | typeMap.put(Types.BOOLEAN, JavaTypeEnum.TYPE_BOOLEAN); 49 | typeMap.put(Types.CHAR, JavaTypeEnum.TYPE_STRING); 50 | typeMap.put(Types.CLOB, JavaTypeEnum.TYPE_STRING); 51 | typeMap.put(Types.DATALINK, JavaTypeEnum.TYPE_STRING); 52 | typeMap.put(Types.DATE, JavaTypeEnum.TYPE_DATE); 53 | typeMap.put(Types.DISTINCT, JavaTypeEnum.TYPE_OBJECT); 54 | typeMap.put(Types.DOUBLE, JavaTypeEnum.TYPE_DOUBLE); 55 | typeMap.put(Types.FLOAT, JavaTypeEnum.TYPE_DOUBLE); 56 | typeMap.put(Types.INTEGER, JavaTypeEnum.TYPE_INTEGER); 57 | typeMap.put(Types.JAVA_OBJECT, JavaTypeEnum.TYPE_OBJECT); 58 | typeMap.put(Jdbc4Types.LONGNVARCHAR, JavaTypeEnum.TYPE_STRING); 59 | typeMap.put(Types.LONGVARBINARY, JavaTypeEnum.TYPE_BYTE_ARRAY); 60 | typeMap.put(Types.LONGVARCHAR, JavaTypeEnum.TYPE_STRING); 61 | typeMap.put(Jdbc4Types.NCHAR, JavaTypeEnum.TYPE_STRING); 62 | typeMap.put(Jdbc4Types.NCLOB, JavaTypeEnum.TYPE_STRING); 63 | typeMap.put(Jdbc4Types.NVARCHAR, JavaTypeEnum.TYPE_STRING); 64 | typeMap.put(Types.NULL, JavaTypeEnum.TYPE_OBJECT); 65 | typeMap.put(Types.OTHER, JavaTypeEnum.TYPE_OBJECT); 66 | typeMap.put(Types.REAL, JavaTypeEnum.TYPE_FLOAT); 67 | typeMap.put(Types.REF, JavaTypeEnum.TYPE_OBJECT); 68 | typeMap.put(Types.SMALLINT, JavaTypeEnum.TYPE_SHORT); 69 | typeMap.put(Types.STRUCT, JavaTypeEnum.TYPE_OBJECT); 70 | typeMap.put(Types.TIME, JavaTypeEnum.TYPE_DATE); 71 | typeMap.put(Types.TIMESTAMP, JavaTypeEnum.TYPE_TIMESTAMP); 72 | typeMap.put(Types.TINYINT, JavaTypeEnum.TYPE_BYTE); 73 | typeMap.put(Types.VARBINARY, JavaTypeEnum.TYPE_BYTE_ARRAY); 74 | typeMap.put(Types.VARCHAR, JavaTypeEnum.TYPE_STRING); 75 | typeMap.put(Types.DECIMAL, JavaTypeEnum.TYPE_BIG_DECIMAL); 76 | typeMap.put(Types.NUMERIC, JavaTypeEnum.TYPE_BIG_DECIMAL); 77 | } 78 | 79 | /** 80 | * 获取java数据类型 81 | * 82 | * @param jdbcType 数据库类型 83 | * @param isFullJavaType 是否获取java类型的全路径 84 | * @return java数据类型全路径 85 | */ 86 | public static String getJavaType(int jdbcType, boolean isFullJavaType) { 87 | return isFullJavaType ? typeMap.get(jdbcType).getFullName() : typeMap.get(jdbcType).getShortName(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/model/util/Jdbc4Types.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2018 恒宇少年 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.gitee.hengboy.builder.core.database.model.util; 17 | 18 | /** 19 | * JDBC 4 类型 20 | * 21 | * @author:于起宇 22 | * =============================== 23 | * Created with IDEA. 24 | * Date:2018/7/8 25 | * Time:5:28 PM 26 | * 简书:http://www.jianshu.com/u/092df3f77bca 27 | * ================================ 28 | */ 29 | public class Jdbc4Types { 30 | public static final int LONGNVARCHAR = -16; 31 | public static final int NVARCHAR = -9; 32 | public static final int NCHAR = -15; 33 | public static final int NCLOB = 2011; 34 | 35 | private Jdbc4Types() { 36 | 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/database/model/util/JdbcTypeResolver.java: -------------------------------------------------------------------------------- 1 | 2 | package com.gitee.hengboy.builder.core.database.model.util; 3 | /** 4 | * Copyright 2018 恒宇少年 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | import java.sql.Types; 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | /** 23 | * JDBC字段类型装载器 24 | * 25 | * @author:于起宇 26 | * =============================== 27 | * Created with IDEA. 28 | * Date:2018/7/8 29 | * Time:6:23 PM 30 | * 简书:http://www.jianshu.com/u/092df3f77bca 31 | * ================================ 32 | */ 33 | public class JdbcTypeResolver { 34 | 35 | private static Map typeToName; 36 | private static Map nameToType; 37 | private static final String TYPE_ARRAY = "ARRAY"; 38 | private static final String TYPE_BIGINT = "BIGINT"; 39 | private static final String TYPE_BINARY = "BINARY"; 40 | private static final String TYPE_BIT = "BIT"; 41 | private static final String TYPE_BLOB = "BLOB"; 42 | private static final String TYPE_BOOLEAN = "BOOLEAN"; 43 | private static final String TYPE_CHAR = "CHAR"; 44 | private static final String TYPE_CLOB = "CLOB"; 45 | private static final String TYPE_DATALINK = "DATALINK"; 46 | private static final String TYPE_DATE = "DATE"; 47 | private static final String TYPE_DECIMAL = "DECIMAL"; 48 | private static final String TYPE_DISTINCT = "DISTINCT"; 49 | private static final String TYPE_DOUBLE = "DOUBLE"; 50 | private static final String TYPE_FLOAT = "FLOAT"; 51 | private static final String TYPE_INTEGER = "INTEGER"; 52 | private static final String TYPE_JAVA_OBJECT = "JAVA_OBJECT"; 53 | private static final String TYPE_LONGVARBINARY = "LONGVARBINARY"; 54 | private static final String TYPE_LONGVARCHAR = "LONGVARCHAR"; 55 | private static final String TYPE_NCHAR = "NCHAR"; 56 | private static final String TYPE_NCLOB = "NCLOB"; 57 | private static final String TYPE_NVARCHAR = "NVARCHAR"; 58 | private static final String TYPE_LONGNVARCHAR = "LONGNVARCHAR"; 59 | private static final String TYPE_NULL = "NULL"; 60 | private static final String TYPE_NUMERIC = "NUMERIC"; 61 | private static final String TYPE_OTHER = "OTHER"; 62 | private static final String TYPE_REAL = "REAL"; 63 | private static final String TYPE_REF = "REF"; 64 | private static final String TYPE_SMALLINT = "SMALLINT"; 65 | private static final String TYPE_STRUCT = "STRUCT"; 66 | private static final String TYPE_TIME = "TIME"; 67 | private static final String TYPE_TIMESTAMP = "TIMESTAMP"; 68 | private static final String TYPE_TINYINT = "TINYINT"; 69 | private static final String TYPE_VARBINARY = "VARBINARY"; 70 | private static final String TYPE_VARCHAR = "VARCHAR"; 71 | 72 | static { 73 | typeToName = new HashMap(); 74 | typeToName.put(Types.ARRAY, TYPE_ARRAY); 75 | typeToName.put(Types.BIGINT, TYPE_BIGINT); 76 | typeToName.put(Types.BINARY, TYPE_BINARY); 77 | typeToName.put(Types.BIT, TYPE_BIT); 78 | typeToName.put(Types.BLOB, TYPE_BLOB); 79 | typeToName.put(Types.BOOLEAN, TYPE_BOOLEAN); 80 | typeToName.put(Types.CHAR, TYPE_CHAR); 81 | typeToName.put(Types.CLOB, TYPE_CLOB); 82 | typeToName.put(Types.DATALINK, TYPE_DATALINK); 83 | typeToName.put(Types.DATE, TYPE_DATE); 84 | typeToName.put(Types.DECIMAL, TYPE_DECIMAL); 85 | typeToName.put(Types.DISTINCT, TYPE_DISTINCT); 86 | typeToName.put(Types.DOUBLE, TYPE_DOUBLE); 87 | typeToName.put(Types.FLOAT, TYPE_FLOAT); 88 | typeToName.put(Types.INTEGER, TYPE_INTEGER); 89 | typeToName.put(Types.JAVA_OBJECT, TYPE_JAVA_OBJECT); 90 | typeToName.put(Types.LONGVARBINARY, TYPE_LONGVARBINARY); 91 | typeToName.put(Types.LONGVARCHAR, TYPE_LONGVARCHAR); 92 | typeToName.put(Jdbc4Types.NCHAR, TYPE_NCHAR); 93 | typeToName.put(Jdbc4Types.NCLOB, TYPE_NCLOB); 94 | typeToName.put(Jdbc4Types.NVARCHAR, TYPE_NVARCHAR); 95 | typeToName.put(Jdbc4Types.LONGNVARCHAR, TYPE_LONGNVARCHAR); 96 | typeToName.put(Types.NULL, TYPE_NULL); 97 | typeToName.put(Types.NUMERIC, TYPE_NUMERIC); 98 | typeToName.put(Types.OTHER, TYPE_OTHER); 99 | typeToName.put(Types.REAL, TYPE_REAL); 100 | typeToName.put(Types.REF, TYPE_REF); 101 | typeToName.put(Types.SMALLINT, TYPE_SMALLINT); 102 | typeToName.put(Types.STRUCT, TYPE_STRUCT); 103 | typeToName.put(Types.TIME, TYPE_TIME); 104 | typeToName.put(Types.TIMESTAMP, TYPE_TIMESTAMP); 105 | typeToName.put(Types.TINYINT, TYPE_TINYINT); 106 | typeToName.put(Types.VARBINARY, TYPE_VARBINARY); 107 | typeToName.put(Types.VARCHAR, TYPE_VARCHAR); 108 | 109 | nameToType = new HashMap(); 110 | nameToType.put(TYPE_ARRAY, Types.ARRAY); 111 | nameToType.put(TYPE_BIGINT, Types.BIGINT); 112 | nameToType.put(TYPE_BINARY, Types.BINARY); 113 | nameToType.put(TYPE_BIT, Types.BIT); 114 | nameToType.put(TYPE_BLOB, Types.BLOB); 115 | nameToType.put(TYPE_BOOLEAN, Types.BOOLEAN); 116 | nameToType.put(TYPE_CHAR, Types.CHAR); 117 | nameToType.put(TYPE_CLOB, Types.CLOB); 118 | nameToType.put(TYPE_DATALINK, Types.DATALINK); 119 | nameToType.put(TYPE_DATE, Types.DATE); 120 | nameToType.put(TYPE_DECIMAL, Types.DECIMAL); 121 | nameToType.put(TYPE_DISTINCT, Types.DISTINCT); 122 | nameToType.put(TYPE_DOUBLE, Types.DOUBLE); 123 | nameToType.put(TYPE_FLOAT, Types.FLOAT); 124 | nameToType.put(TYPE_INTEGER, Types.INTEGER); 125 | nameToType.put(TYPE_JAVA_OBJECT, Types.JAVA_OBJECT); 126 | nameToType.put(TYPE_LONGVARBINARY, Types.LONGVARBINARY); 127 | nameToType.put(TYPE_LONGVARCHAR, Types.LONGVARCHAR); 128 | nameToType.put(TYPE_NCHAR, Jdbc4Types.NCHAR); 129 | nameToType.put(TYPE_NCLOB, Jdbc4Types.NCLOB); 130 | nameToType.put(TYPE_NVARCHAR, Jdbc4Types.NVARCHAR); 131 | nameToType.put(TYPE_LONGNVARCHAR, Jdbc4Types.LONGNVARCHAR); 132 | nameToType.put(TYPE_NULL, Types.NULL); 133 | nameToType.put(TYPE_NUMERIC, Types.NUMERIC); 134 | nameToType.put(TYPE_OTHER, Types.OTHER); 135 | nameToType.put(TYPE_REAL, Types.REAL); 136 | nameToType.put(TYPE_REF, Types.REF); 137 | nameToType.put(TYPE_SMALLINT, Types.SMALLINT); 138 | nameToType.put(TYPE_STRUCT, Types.STRUCT); 139 | nameToType.put(TYPE_TIME, Types.TIME); 140 | nameToType.put(TYPE_TIMESTAMP, Types.TIMESTAMP); 141 | nameToType.put(TYPE_TINYINT, Types.TINYINT); 142 | nameToType.put(TYPE_VARBINARY, Types.VARBINARY); 143 | nameToType.put(TYPE_VARCHAR, Types.VARCHAR); 144 | } 145 | 146 | private JdbcTypeResolver() { 147 | super(); 148 | } 149 | 150 | public static String getJdbcTypeName(int jdbcType) { 151 | String answer = typeToName.get(jdbcType); 152 | if (answer == null) { 153 | answer = TYPE_OTHER; 154 | } 155 | 156 | return answer; 157 | } 158 | 159 | public static int getJdbcType(String jdbcTypeName) { 160 | Integer answer = nameToType.get(jdbcTypeName); 161 | if (answer == null) { 162 | answer = Types.OTHER; 163 | } 164 | 165 | return answer; 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/engine/AbstractEngineTemplate.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.engine; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 19 | import com.gitee.hengboy.builder.common.util.StringUtil; 20 | import com.gitee.hengboy.builder.core.configuration.BuilderConfiguration; 21 | import com.gitee.hengboy.builder.core.configuration.TemplateConfiguration; 22 | import com.gitee.hengboy.builder.core.database.DataBase; 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | 26 | import java.io.File; 27 | import java.util.List; 28 | 29 | /** 30 | * 驱动抽象类 31 | * 32 | * @author:于起宇 =============================== 33 | * Created with IDEA. 34 | * Date:2018/7/12 35 | * Time:2:22 PM 36 | * 简书:http://www.jianshu.com/u/092df3f77bca 37 | * ================================ 38 | */ 39 | public abstract class AbstractEngineTemplate implements EngineTemplate { 40 | /** 41 | * logger instance 42 | */ 43 | static Logger logger = LoggerFactory.getLogger(AbstractEngineTemplate.class); 44 | 45 | /** 46 | * 数据库对象实例 47 | */ 48 | protected DataBase dataBase; 49 | /** 50 | * 自动生成参数实体实例 51 | */ 52 | protected CodeBuilderProperties codeBuilderProperties; 53 | /** 54 | * 系统分隔符 55 | */ 56 | protected static final String SEPARATOR = File.separator; 57 | /** 58 | * 自动生成文件的后缀名 59 | */ 60 | protected static final String FILE_SUFFIX = ".java"; 61 | /** 62 | * package 分隔符 63 | */ 64 | protected static final String PACKAGE_SPLIT = "."; 65 | 66 | /** 67 | * 构造函数初始化数据库对象实例、代码生成配置实体 68 | * 69 | * @param dataBase 数据库对象实例 70 | * @param codeBuilderProperties 代码生成配置实体 71 | */ 72 | public AbstractEngineTemplate(DataBase dataBase, CodeBuilderProperties codeBuilderProperties) { 73 | this.dataBase = dataBase; 74 | this.codeBuilderProperties = codeBuilderProperties; 75 | } 76 | 77 | /** 78 | * 执行输出日志 79 | * 打印本次执行的基本信息 80 | * 81 | * @param tablesSize 本次生成表格的数量 82 | */ 83 | public void invokeConsoleLog(int tablesSize) { 84 | logger.info("Code-Builder >>> 本次有{}个表参与生成.", tablesSize); 85 | logger.info("Code-Builder >>> 执行项目目录:{}", getProjectDir()); 86 | logger.info("Code-Builder >>> 生成目录:{}", getBasePackageTargetDir()); 87 | logger.info("Code-Builder >>> Builder根目录:{}", getBaseBuilderDir()); 88 | } 89 | 90 | /** 91 | * 循环生成文件 92 | * 93 | * @param tableNames 数据表列表 94 | */ 95 | public void loopProcess(List tableNames) { 96 | for (String tableName : tableNames) { 97 | logger.info("Auto Builder Table > 【{}】", tableName); 98 | process(dataBase.getTable(tableName)); 99 | } 100 | // 执行生成日志输出 101 | invokeConsoleLog(tableNames.size()); 102 | } 103 | 104 | /** 105 | * 获取自动化配置对象实例 106 | * 从builder.yml配置文件内自动映射为配置类实例 107 | * 108 | * @return 配置对象实例 109 | */ 110 | protected BuilderConfiguration getConfiguration() { 111 | return codeBuilderProperties.getBuilder(); 112 | } 113 | 114 | /** 115 | * 获取项目目录 116 | * 117 | * @return 项目根路径 118 | */ 119 | protected String getProjectDir() { 120 | return codeBuilderProperties.getProjectBaseDir() + SEPARATOR; 121 | } 122 | 123 | /** 124 | * 获取生成目标目录地址 125 | * 126 | * @return 目标根路径 127 | */ 128 | protected String getBaseTargetDir() { 129 | StringBuffer baseTargetDir = new StringBuffer(); 130 | // 项目根地址 131 | baseTargetDir.append(getProjectDir()); 132 | // 生成目标目录 133 | baseTargetDir.append(codeBuilderProperties.getTargetDir()); 134 | baseTargetDir.append(SEPARATOR); 135 | return baseTargetDir.toString(); 136 | } 137 | 138 | /** 139 | * 获取builder基础目录地址 140 | * 141 | * @return builder根路径 142 | */ 143 | protected String getBaseBuilderDir() { 144 | StringBuffer builderDir = new StringBuffer(); 145 | // 项目根地址 146 | builderDir.append(codeBuilderProperties.getProjectBaseDir()); 147 | // 系统分隔符 148 | builderDir.append(SEPARATOR); 149 | 150 | // builder根地址 151 | builderDir.append(codeBuilderProperties.getBuilderDir()); 152 | // 系统分隔符 153 | builderDir.append(SEPARATOR); 154 | return builderDir.toString(); 155 | } 156 | 157 | /** 158 | * 获取模板创建文件后的包名 159 | * 160 | * @param templateConfiguration 模板配置对象 161 | * @return 包名 162 | */ 163 | protected String getTemplatePackageName(TemplateConfiguration templateConfiguration) { 164 | // 包名前缀 165 | StringBuffer packageName = new StringBuffer(codeBuilderProperties.getBuilder().getPackagePrefix()); 166 | // 默认包名 167 | if (StringUtil.isNotEmpty(templateConfiguration.getPackageName())) { 168 | packageName.append(PACKAGE_SPLIT); 169 | // 转换为小写 170 | packageName.append(templateConfiguration.getPackageName().toLowerCase()); 171 | } 172 | return packageName.toString(); 173 | } 174 | 175 | /** 176 | * 获取生成目标目录 + package目录格式化后的根地址 177 | * 178 | * @return 存在包名的目录根路径 179 | */ 180 | protected String getBasePackageTargetDir() { 181 | // 获取builder配置信息 182 | BuilderConfiguration builderConfiguration = codeBuilderProperties.getBuilder(); 183 | StringBuffer basePackageDir = new StringBuffer(); 184 | // 生成文件的目标根路径 185 | basePackageDir.append(getBaseTargetDir()); 186 | 187 | // 是否存在自定义的package前缀 188 | // 存在前缀添加到路径内 189 | if (StringUtil.isNotEmpty(builderConfiguration.getDiffSysPackagePrefix())) { 190 | basePackageDir.append(builderConfiguration.getDiffSysPackagePrefix()); 191 | } 192 | // 系统分隔符 193 | basePackageDir.append(SEPARATOR); 194 | return basePackageDir.toString(); 195 | } 196 | 197 | /** 198 | * 获取模板生成文件后的类名 199 | * 200 | * @param templateConfiguration 默认配置信息 201 | * @param entityName 数据表对应的实体名称 202 | * @return Class 名称 203 | */ 204 | protected String getTemplateClassName(TemplateConfiguration templateConfiguration, String entityName) { 205 | StringBuffer className = new StringBuffer(); 206 | // 追加文件前缀名 207 | if (StringUtil.isNotEmpty(templateConfiguration.getFilePrefix())) { 208 | className.append(StringUtil.getCamelCaseString(templateConfiguration.getFilePrefix(), true)); 209 | } 210 | // 实体类名称 211 | className.append(entityName); 212 | // 追加文件后缀名 213 | if (StringUtil.isNotEmpty(templateConfiguration.getFileSuffix())) { 214 | className.append(StringUtil.getCamelCaseString(templateConfiguration.getFileSuffix(), true)); 215 | } 216 | return className.toString(); 217 | } 218 | 219 | /** 220 | * 获取新文件的全名称 221 | * 如:XxxEntity.java 222 | * 223 | * @param templateConfiguration 模板配置对象 224 | * @param entityName 数据表对应的实体名称 225 | * @return 新文件名称 226 | */ 227 | protected String getTemplateNewFileName(TemplateConfiguration templateConfiguration, String entityName) { 228 | StringBuffer fileName = new StringBuffer(); 229 | // 目标package的根目录 230 | fileName.append(getBasePackageTargetDir()); 231 | 232 | // 是否配置了模板创建文件后所属的package目录 233 | if (StringUtil.isNotEmpty(templateConfiguration.getPackageName())) { 234 | fileName.append(templateConfiguration.getPackageName()); 235 | fileName.append(SEPARATOR); 236 | } 237 | // 类名 238 | fileName.append(getTemplateClassName(templateConfiguration, entityName)); 239 | // 文件扩展名 240 | fileName.append(FILE_SUFFIX); 241 | return fileName.toString(); 242 | } 243 | 244 | /** 245 | * 循环创建package 246 | * 根据builder.yml配置文件内的参数packagePrefix进行自动创建package包名的文件夹 247 | * 如:com.code.builder 248 | * 则自动创建com/code/builder文件夹 249 | * 250 | * @param templateConfiguration 模板配置 251 | */ 252 | protected void loopCreatePackage(TemplateConfiguration templateConfiguration) { 253 | // 目录地址 254 | StringBuffer basePackagePath = new StringBuffer(); 255 | // 目标根地址 256 | basePackagePath.append(getBasePackageTargetDir()); 257 | // 模板生成文件目标独有的package 258 | if (StringUtil.isNotEmpty(templateConfiguration.getPackageName())) { 259 | basePackagePath.append(templateConfiguration.getPackageName()); 260 | } 261 | // 执行创建目录 262 | File basePackage = new File(basePackagePath.toString()); 263 | basePackage.mkdirs(); 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/engine/EngineTemplate.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.engine; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | import com.gitee.hengboy.builder.core.database.model.Table; 18 | 19 | import java.util.List; 20 | 21 | /** 22 | * 驱动模板接口 23 | * 目前仅实现freemarker模板 24 | * 25 | * @author:于起宇 26 | * =============================== 27 | * Created with IDEA. 28 | * Date:2018/7/8 29 | * Time:5:15 PM 30 | * 简书:http://www.jianshu.com/u/092df3f77bca 31 | * ================================ 32 | */ 33 | public interface EngineTemplate { 34 | /** 35 | * 单个数据表生成文件 36 | * 37 | * @param table 数据表对象 38 | */ 39 | void process(Table table); 40 | 41 | /** 42 | * 循环执行生成文件 43 | * 44 | * @param tableNames 表名列表 45 | */ 46 | void loopProcess(List tableNames); 47 | } 48 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/engine/EngineTemplateFactory.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.engine; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 19 | import com.gitee.hengboy.builder.common.enums.EngineTypeEnum; 20 | import com.gitee.hengboy.builder.common.enums.ErrorEnum; 21 | import com.gitee.hengboy.builder.common.exception.CodeBuilderException; 22 | import com.gitee.hengboy.builder.core.database.DataBase; 23 | 24 | import java.lang.reflect.Constructor; 25 | 26 | /** 27 | * 驱动模板动态工厂 28 | * 29 | * @author:于起宇 =============================== 30 | * Created with IDEA. 31 | * Date:2018/7/11 32 | * Time:5:55 PM 33 | * 简书:http://www.jianshu.com/u/092df3f77bca 34 | * ================================ 35 | */ 36 | public class EngineTemplateFactory { 37 | private EngineTemplateFactory() { 38 | } 39 | 40 | /** 41 | * 根据驱动枚举动态初始化获取驱动实现类实例 42 | * 43 | * @param engineTypeEnum 驱动枚举 44 | * @param codeBuilderProperties 配置参数实体 45 | * @param dataBase 数据库连接实例 46 | * @return 驱动模板实例 47 | */ 48 | public static EngineTemplate newInstance(EngineTypeEnum engineTypeEnum, DataBase dataBase, CodeBuilderProperties codeBuilderProperties) { 49 | try { 50 | // 获取数据库实现类的构造函数 51 | Constructor constructor = engineTypeEnum.getImplClass().getConstructor(DataBase.class, CodeBuilderProperties.class); 52 | // 反射获取数据库实现类实例 53 | return (EngineTemplate) constructor.newInstance(dataBase, codeBuilderProperties); 54 | } catch (Exception e) { 55 | e.printStackTrace(); 56 | } 57 | throw new CodeBuilderException(ErrorEnum.NOT_ALLOW_ENGINE); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/engine/impl/FreemarkerEngineImpl.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.engine.impl; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 19 | import com.gitee.hengboy.builder.common.enums.EngineTypeEnum; 20 | import com.gitee.hengboy.builder.core.configuration.BuilderConfiguration; 21 | import com.gitee.hengboy.builder.core.configuration.TemplateConfiguration; 22 | import com.gitee.hengboy.builder.core.database.DataBase; 23 | import com.gitee.hengboy.builder.core.database.model.Table; 24 | import com.gitee.hengboy.builder.core.engine.AbstractEngineTemplate; 25 | import com.gitee.hengboy.builder.core.engine.model.DataModelEntity; 26 | import freemarker.template.Configuration; 27 | import freemarker.template.Template; 28 | 29 | import java.io.*; 30 | import java.util.Locale; 31 | 32 | /** 33 | * 使用freemarker模板驱动实现类 34 | * 35 | * @author:于起宇 =============================== 36 | * Created with IDEA. 37 | * Date:2018/7/8 38 | * Time:5:20 PM 39 | * 简书:http://www.jianshu.com/u/092df3f77bca 40 | * ================================ 41 | */ 42 | public class FreemarkerEngineImpl extends AbstractEngineTemplate { 43 | /** 44 | * freemarker配置对象实例化 45 | * 采用2.3.28版本 46 | */ 47 | private Configuration configuration = new Configuration(Configuration.VERSION_2_3_28); 48 | 49 | /** 50 | * 默认字符集 51 | */ 52 | static final String DEFAULT_ENCODING = "UTF-8"; 53 | /** 54 | * 默认国际化 55 | */ 56 | static final String DEFAULT_LOCALE = "zh_CN"; 57 | 58 | public FreemarkerEngineImpl(DataBase dataBase, CodeBuilderProperties codeBuilderProperties) { 59 | super(dataBase, codeBuilderProperties); 60 | } 61 | 62 | /** 63 | * 设置freemarker全局配置参数 64 | */ 65 | { 66 | try { 67 | configuration.setDirectoryForTemplateLoading(new File(getBaseBuilderDir() + EngineTypeEnum.FREEMARKER.getTemplateDirName())); 68 | configuration.setDefaultEncoding(DEFAULT_ENCODING); 69 | configuration.setLocale(new Locale(DEFAULT_LOCALE)); 70 | } catch (Exception e) { 71 | e.printStackTrace(); 72 | } 73 | } 74 | 75 | /** 76 | * 构建指定表的实体 77 | * 78 | * @param table 数据表对象 79 | */ 80 | public void process(Table table) { 81 | try { 82 | // 获取配置 83 | BuilderConfiguration builderConfiguration = getConfiguration(); 84 | // 遍历生成文件 85 | for (TemplateConfiguration templateConfiguration : builderConfiguration.getTemplates()) { 86 | // 创建package 87 | loopCreatePackage(templateConfiguration); 88 | // freemarker模板 89 | Template template = configuration.getTemplate(templateConfiguration.getName()); 90 | // 创建文件 91 | File file = new File(getTemplateNewFileName(templateConfiguration, table.getEntityName())); 92 | // 写入freemarker模板内容 93 | Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), DEFAULT_ENCODING)); 94 | 95 | /* 96 | * 构建数据模型实体 97 | * 1. 设置当前模板创建类的包名 98 | * 2. 设置当前模板创建类的类名 99 | * 3. 设置数据表格对象 100 | */ 101 | DataModelEntity dataModelEntity = DataModelEntity.builder() 102 | .packageName(getTemplatePackageName(templateConfiguration)) 103 | .className(getTemplateClassName(templateConfiguration, table.getEntityName())) 104 | .table(table) 105 | .build(); 106 | 107 | // 执行生成 108 | template.process(dataModelEntity, out); 109 | } 110 | 111 | } catch (Exception e) { 112 | e.printStackTrace(); 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/engine/model/DataModelEntity.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.engine.model; 2 | 3 | import com.gitee.hengboy.builder.core.database.model.Table; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | 7 | /** 8 | * 模板结果实体 9 | * 没一个模板都会有该实体的对象实例传递 10 | * 比如:freemarker在process时传递该实体的实例到freemarker模板内 11 | * 12 | * @author:于起宇 =============================== 13 | * Created with IDEA. 14 | * Date:2018/7/17 15 | * Time:10:29 AM 16 | * 简书:http://www.jianshu.com/u/092df3f77bca 17 | * ================================ 18 | */ 19 | @Data 20 | @Builder 21 | public class DataModelEntity { 22 | /** 23 | * 表格实例 24 | */ 25 | private Table table; 26 | /** 27 | * 类名 28 | * 如:UserInfoEntity 29 | */ 30 | private String className; 31 | /** 32 | * 包名 33 | * 如:com.xxx.xxx.user 34 | */ 35 | private String packageName; 36 | } 37 | -------------------------------------------------------------------------------- /code-builder-core/src/main/java/com/gitee/hengboy/builder/core/invoke/CodeBuilderInvoke.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.core.invoke; 2 | 3 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 4 | import com.gitee.hengboy.builder.common.enums.ErrorEnum; 5 | import com.gitee.hengboy.builder.common.exception.CodeBuilderException; 6 | import com.gitee.hengboy.builder.common.util.StringUtil; 7 | import com.gitee.hengboy.builder.core.database.DataBase; 8 | import com.gitee.hengboy.builder.core.database.DataBaseFactory; 9 | import com.gitee.hengboy.builder.core.engine.EngineTemplate; 10 | import com.gitee.hengboy.builder.core.engine.EngineTemplateFactory; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | import java.util.List; 15 | 16 | /** 17 | * 自动生成执行类型 18 | * @author:于起宇 19 | * =============================== 20 | * Created with IDEA. 21 | * Date:2018/7/19 22 | * Time:1:59 PM 23 | * 简书:http://www.jianshu.com/u/092df3f77bca 24 | * ================================ 25 | */ 26 | public class CodeBuilderInvoke { 27 | 28 | private CodeBuilderInvoke() { } 29 | 30 | /** 31 | * logger instance 32 | */ 33 | static Logger logger = LoggerFactory.getLogger(CodeBuilderInvoke.class); 34 | 35 | /** 36 | * 执行构造入口方法 37 | * 该方法用于maven-plugin、starter两个地方 38 | * 39 | * @param codeBuilderProperties 自动生成参数实体 40 | */ 41 | public static void invoke(CodeBuilderProperties codeBuilderProperties) { 42 | if (!codeBuilderProperties.isExecute()) { 43 | logger.info("未开启自动代码生成,如需生成实体类请配置【execute=true】"); 44 | return; 45 | } 46 | 47 | // 获取数据库对象 48 | DataBase dataBase = DataBaseFactory.newInstance(codeBuilderProperties); 49 | // 获取驱动模板 50 | EngineTemplate engineTemplate = EngineTemplateFactory.newInstance(codeBuilderProperties.getEngineTypeEnum(), dataBase, codeBuilderProperties); 51 | // 获取表名列表 52 | List tableNames = getTables(dataBase, codeBuilderProperties); 53 | // 执行循环自动生成文件 54 | engineTemplate.loopProcess(tableNames); 55 | // 关闭数据库连接 56 | dataBase.closeConnection(); 57 | } 58 | 59 | /** 60 | * 获取需要自动生成的表列表 61 | * 62 | * @param dataBase 数据库对象实例 63 | * @return 64 | */ 65 | private static List getTables(DataBase dataBase, CodeBuilderProperties codeBuilderProperties) { 66 | List tables = codeBuilderProperties.getTables(); 67 | String generatorByPattern = codeBuilderProperties.getGeneratorByPattern(); 68 | /* 69 | * 根据配置tables参数表名进行构建生成 70 | * 优先级高于generatorByPattern 71 | */ 72 | if (null != tables && tables.size() > 0) { 73 | logger.info("Using table name to generate code automatically, please wait..."); 74 | return tables; 75 | } 76 | /* 77 | * 如果配置generatorByPattern参数,优先级高于tables 78 | */ 79 | else if (StringUtil.isNotEmpty(generatorByPattern)) { 80 | logger.info("Using expression method to generate code automatically, please wait..."); 81 | return dataBase.getTableNames(generatorByPattern); 82 | } 83 | throw new CodeBuilderException(ErrorEnum.NO_BUILDER_TABLE); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /code-builder-maven-plugin-sample/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | code-builder 7 | com.gitee.hengboy 8 | 1.0.5.RELEASE 9 | 10 | 4.0.0 11 | Code-Builder Maven插件示例 12 | code-builder-maven-plugin-sample 13 | 14 | 集成code-builder-maven-plugin插件形式 15 | 16 | 17 | 18 | 19 | 20 | 21 | com.gitee.hengboy 22 | mybatis-enhance-spring-boot-starter 23 | 1.0.3.RELEASE 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | com.gitee.hengboy 32 | code-builder-maven-plugin 33 | 1.0.5.RELEASE 34 | 35 | 36 | 37 | generator 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | mysql 46 | mysql-connector-java 47 | 5.1.46 48 | 49 | 50 | 51 | 52 | 53 | true 54 | 55 | 56 | 57 | 58 | 59 | 60 | xxxx 61 | xxxxx 62 | xxxx 63 | jdbc:mysql://xxx.xxx.xx.xxx:3306 64 | 65 | 66 | 67 |

sys_menu_info
68 | sys_role_info
69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | Sys 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | com.code.builder.sample 88 | 89 | 90 | 91 | 92 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | org.apache.maven.plugins 109 | maven-deploy-plugin 110 | 2.8.2 111 | 112 | true 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /code-builder-maven-plugin-sample/src/main/resources/templates/builder/freemarker/entity.ftl: -------------------------------------------------------------------------------- 1 | <#if (packageName)??> 2 | package ${packageName}; 3 | 4 | <#if (table.hasSqlDate)> 5 | import java.sql.Date; 6 | 7 | <#if (table.hasTimeStamp)> 8 | import java.sql.Timestamp; 9 | 10 | <#if (table.hasBigDecimal)> 11 | import java.math.BigDecimal; 12 | 13 | import com.gitee.hengboy.mybatis.enhance.common.annotation.Column; 14 | import com.gitee.hengboy.mybatis.enhance.common.annotation.Id; 15 | import com.gitee.hengboy.mybatis.enhance.common.annotation.Table; 16 | import com.gitee.hengboy.mybatis.enhance.common.enums.KeyGeneratorTypeEnum; 17 | import lombok.Data; 18 | 19 | /** 20 | *

本类由Code-Builder自动生成

21 | *

表名: ${table.tableName} - ${table.remark} - 数据实体

22 | * 23 | * @author Code-Builder 24 | * @since 恒宇少年 25 | * =============================== 26 | * Created with Code-Builder. 27 | * User: 28 | * Date:${.now} 29 | * 简书:http://www.jianshu.com/u/092df3f77bca 30 | * 码云:https://gitee.com/hengboy 31 | * GitHub:https://github.com/hengyuboy 32 | * ================================ 33 | */ 34 | @Data 35 | @Table(name = "${table.tableName}") 36 | public class ${className} { 37 | <#list table.primaryKeys as key> 38 | /** 39 | * ${key.columnName} - ${key.remark} 40 | */ 41 | <#if (key.autoincrement)> 42 | @Id(generatorType = KeyGeneratorTypeEnum.AUTO) 43 | <#else> 44 | @Id(generatorType = KeyGeneratorTypeEnum.UUID) 45 | 46 | @Column(name="${key.columnName}") 47 | private ${key.javaType} ${key.javaProperty}; 48 | 49 | <#list table.columns as column> 50 | <#if (!column.primaryKey)> 51 | /** 52 | * ${column.columnName} - ${column.remark} 53 | */ 54 | @Column(name="${column.columnName}"<#if (column.defaultValue)??>,insertable = false) 55 | private ${column.javaType} ${column.javaProperty}; 56 | 57 | 58 | } -------------------------------------------------------------------------------- /code-builder-maven-plugin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | code-builder 7 | com.gitee.hengboy 8 | 1.0.5.RELEASE 9 | 10 | 4.0.0 11 | code-builder-maven-plugin 12 | maven-plugin 13 | 14 | 15 | 16 | com.gitee.hengboy 17 | code-builder-core 18 | ${code.builder.core.version} 19 | 20 | 21 | 22 | org.apache.maven 23 | maven-plugin-api 24 | ${maven.plugin.api.version} 25 | 26 | 27 | 28 | org.apache.maven.plugin-tools 29 | maven-plugin-annotations 30 | ${maven.plugin.annotation.version} 31 | provided 32 | 33 | 34 | -------------------------------------------------------------------------------- /code-builder-maven-plugin/src/main/java/com/gitee/hengboy/builder/CodeBuilderMojo.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder; 2 | /** 3 | * Copyright 2018 恒宇少年 4 | *

5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | *

9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | *

11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 19 | import com.gitee.hengboy.builder.common.enums.DbTypeEnum; 20 | import com.gitee.hengboy.builder.common.enums.EngineTypeEnum; 21 | import com.gitee.hengboy.builder.core.configuration.BuilderConfiguration; 22 | import com.gitee.hengboy.builder.core.invoke.CodeBuilderInvoke; 23 | import org.apache.maven.plugin.AbstractMojo; 24 | import org.apache.maven.plugin.MojoExecutionException; 25 | import org.apache.maven.plugin.MojoFailureException; 26 | import org.apache.maven.plugins.annotations.Execute; 27 | import org.apache.maven.plugins.annotations.LifecyclePhase; 28 | import org.apache.maven.plugins.annotations.Mojo; 29 | import org.apache.maven.plugins.annotations.Parameter; 30 | 31 | import java.util.List; 32 | 33 | /** 34 | * 代码生成器Maven插件入口类 35 | *

简书:http://www.jianshu.com/u/092df3f77bca

36 | *

码云:https://gitee.com/hengboy

37 | * 38 | * @author 恒宇少年 39 | */ 40 | @Mojo(name = "generator", defaultPhase = LifecyclePhase.COMPILE) 41 | @Execute(phase = LifecyclePhase.COMPILE) 42 | public class CodeBuilderMojo 43 | extends AbstractMojo { 44 | /** 45 | * 是否执行自动生成 46 | * 默认值:不执行 47 | */ 48 | @Parameter(defaultValue = "false", required = true) 49 | private boolean execute; 50 | /** 51 | * 数据库类型 52 | * 自动根据类型加载对应的驱动 53 | * 如:MySQL => com.mysql.jdbc.Driver 54 | */ 55 | @Parameter(defaultValue = "MySQL") 56 | private DbTypeEnum dbType; 57 | /** 58 | * 数据库名称 59 | */ 60 | @Parameter(required = true) 61 | private String dbName; 62 | /** 63 | * 数据库连接地址 64 | * 排除数据库名称 65 | * 如:jdbc:mysql://xxx.xx.xx.xxx:3306 66 | */ 67 | @Parameter(required = true) 68 | private String dbUrl; 69 | /** 70 | * 数据库连接用户名 71 | */ 72 | @Parameter(required = true) 73 | private String dbUserName; 74 | /** 75 | * 数据库连接密码 76 | */ 77 | @Parameter 78 | private String dbPassword; 79 | /** 80 | * 数据库驱动类全局限定名 81 | */ 82 | @Parameter 83 | private String dbDriverClassName; 84 | /** 85 | * 忽略表名的前缀 86 | * 如建表时表名为:sys_menu_info 87 | * 配置忽略前缀为:sys_ 88 | * 生成对应的Class后为:MenuInfo 89 | */ 90 | @Parameter 91 | private String ignoreClassPrefix; 92 | 93 | /** 94 | * 指定生成的表列表 95 | * 根据指定的表名进行生成 96 | * 如: 97 | * 98 | * sys_menu_info
99 | * sys_role_info
100 | *
101 | * 会自动生成sys_menu_info、sys_role_info两张表对应的模板文件 102 | */ 103 | @Parameter 104 | private List tables; 105 | /** 106 | * 根据指定前缀生成 107 | * 如:sys_ 108 | * 会匹配:sys_menu_info、sys_role_info、sys_button_info等表 109 | */ 110 | @Parameter 111 | private String generatorByPattern; 112 | /** 113 | * 驱动模板类型 114 | * 默认值:freemarker 115 | */ 116 | @Parameter(defaultValue = "FREEMARKER") 117 | private EngineTypeEnum engineType; 118 | 119 | /** 120 | * 项目根地址 121 | */ 122 | @Parameter(defaultValue = "${basedir}") 123 | private String projectBaseDir; 124 | 125 | /** 126 | * builder配置文件目录地址 127 | * 这里配置分隔符是"." 128 | * 因为linux、osx、windows下的分隔符不一样 129 | * 需要根据java获取系统的分隔符后格式化 130 | */ 131 | @Parameter(defaultValue = "target.classes.templates.builder") 132 | private String builderDir; 133 | 134 | /** 135 | * 文件生成后目标根地址 136 | */ 137 | @Parameter(defaultValue = "target.generated-sources.java") 138 | private String targetDir; 139 | /** 140 | * 自动生成配置信息实体 141 | */ 142 | @Parameter 143 | private BuilderConfiguration builder; 144 | 145 | /** 146 | * 执行插件入口方法 147 | * - 构造自动构建参数对象 148 | * - 获取数据库对象 149 | * - 获取驱动模型 150 | * - 执行驱动生成文件 151 | * 152 | * @throws MojoExecutionException mojo执行异常 153 | * @throws MojoFailureException mojo错误异常 154 | */ 155 | public void execute() throws MojoExecutionException, MojoFailureException { 156 | try { 157 | /* 158 | * 组装代码生成器所需的实体参数 159 | * 传递到所需配置类 160 | */ 161 | CodeBuilderProperties codeBuilderProperties = CodeBuilderProperties.builder() 162 | .execute(execute) 163 | .dbType(dbType) 164 | .dbName(dbName) 165 | .dbUserName(dbUserName) 166 | .dbPassword(dbPassword) 167 | .dbUrl(dbUrl) 168 | .dbDriverClassName(dbDriverClassName) 169 | .tables(tables) 170 | .generatorByPattern(generatorByPattern) 171 | .ignoreClassPrefix(ignoreClassPrefix) 172 | .projectBaseDir(projectBaseDir) 173 | .builderDir(builderDir) 174 | .targetDir(targetDir) 175 | .builder(builder) 176 | .engineTypeEnum(engineType) 177 | .build(); 178 | 179 | // 执行代码生成 180 | CodeBuilderInvoke.invoke(codeBuilderProperties); 181 | 182 | } catch (Exception e) { 183 | getLog().error("Invoke have errors :" + e.getMessage()); 184 | } 185 | 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /code-builder-spring-boot-autoconfigure/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | code-builder 7 | com.gitee.hengboy 8 | 1.0.5.RELEASE 9 | 10 | 4.0.0 11 | jar 12 | code-builder-spring-boot-autoconfigure 13 | 14 | 15 | 16 | org.springframework.boot 17 | spring-boot-autoconfigure 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-configuration-processor 23 | true 24 | 25 | 26 | 27 | com.gitee.hengboy 28 | code-builder-core 29 | ${code.builder.core.version} 30 | 31 | 32 | com.alibaba 33 | fastjson 34 | 1.2.47 35 | 36 | 37 | -------------------------------------------------------------------------------- /code-builder-spring-boot-autoconfigure/src/main/java/com/gitee/hengboy/builder/spring/boot/autoconfigure/BuilderAutoConfigureProperties.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.spring.boot.autoconfigure; 2 | 3 | import com.gitee.hengboy.builder.common.enums.DbTypeEnum; 4 | import com.gitee.hengboy.builder.common.enums.EngineTypeEnum; 5 | import com.gitee.hengboy.builder.core.configuration.BuilderConfiguration; 6 | import lombok.Data; 7 | import org.springframework.boot.context.properties.ConfigurationProperties; 8 | 9 | import java.util.List; 10 | 11 | import static com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties.CODE_BUILDER_PREFIX; 12 | 13 | /** 14 | * 代码生成自动配置文件 15 | * 16 | * @author:于起宇 =============================== 17 | * Created with IDEA. 18 | * Date:2018/7/19 19 | * Time:11:40 AM 20 | * 简书:http://www.jianshu.com/u/092df3f77bca 21 | * ================================ 22 | */ 23 | @Data 24 | @ConfigurationProperties(prefix = CODE_BUILDER_PREFIX) 25 | public class BuilderAutoConfigureProperties { 26 | 27 | /** 28 | * Properties Prefix 29 | */ 30 | public static final String CODE_BUILDER_PREFIX = "hengboy.code.builder"; 31 | 32 | private boolean execute; 33 | private String ignoreClassPrefix; 34 | private List tables; 35 | private String generatorByPattern; 36 | private DbTypeEnum dbType = DbTypeEnum.MySQL; 37 | private EngineTypeEnum engineTypeEnum = EngineTypeEnum.FREEMARKER; 38 | private String projectBaseDir; 39 | private String builderDir = "target.classes.templates.builder"; 40 | private String targetDir = "target.generated-sources.java"; 41 | private BuilderConfiguration configuration; 42 | } 43 | -------------------------------------------------------------------------------- /code-builder-spring-boot-autoconfigure/src/main/java/com/gitee/hengboy/builder/spring/boot/autoconfigure/CodeBuilderAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.gitee.hengboy.builder.spring.boot.autoconfigure; 2 | 3 | import com.gitee.hengboy.builder.common.CodeBuilderProperties; 4 | import com.gitee.hengboy.builder.core.configuration.BuilderConfiguration; 5 | import com.gitee.hengboy.builder.core.configuration.TemplateConfiguration; 6 | import com.gitee.hengboy.builder.core.invoke.CodeBuilderInvoke; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | import org.springframework.beans.factory.ObjectProvider; 10 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 11 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 12 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 13 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 14 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 15 | import org.springframework.context.annotation.Configuration; 16 | import org.springframework.util.ResourceUtils; 17 | 18 | import javax.sql.DataSource; 19 | 20 | import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX; 21 | 22 | /** 23 | * 代码生成器自动化配置 24 | * 25 | * @author:于起宇 =============================== 26 | * Created with IDEA. 27 | * Date:2018/7/19 28 | * Time:11:37 AM 29 | * 简书:http://www.jianshu.com/u/092df3f77bca 30 | * ================================ 31 | */ 32 | @Configuration 33 | @ConditionalOnClass({BuilderConfiguration.class, TemplateConfiguration.class}) 34 | @ConditionalOnBean(DataSource.class) 35 | @EnableConfigurationProperties(BuilderAutoConfigureProperties.class) 36 | @AutoConfigureAfter(DataSourceAutoConfiguration.class) 37 | public class CodeBuilderAutoConfiguration { 38 | /** 39 | * logger instance 40 | */ 41 | static Logger logger = LoggerFactory.getLogger(CodeBuilderAutoConfiguration.class); 42 | 43 | private BuilderAutoConfigureProperties builderAutoConfigureProperties; 44 | private DataSource dataSource; 45 | 46 | /** 47 | * 初始化BuilderAutoConfigureProperties配置类 48 | * 49 | * @param builderAutoConfigureProperties 代码生成器配置类实例 50 | * @param dataSource 数据源 51 | */ 52 | public CodeBuilderAutoConfiguration(BuilderAutoConfigureProperties builderAutoConfigureProperties, 53 | ObjectProvider dataSource) { 54 | this.builderAutoConfigureProperties = builderAutoConfigureProperties; 55 | this.dataSource = dataSource.getIfAvailable(); 56 | invokeBuilder(); 57 | } 58 | 59 | /** 60 | * Invoke Code Builder 61 | */ 62 | void invokeBuilder() { 63 | try { 64 | CodeBuilderInvoke.invoke( 65 | CodeBuilderProperties.builder() 66 | .execute(builderAutoConfigureProperties.isExecute()) 67 | .dataSource(dataSource) 68 | .dbType(builderAutoConfigureProperties.getDbType()) 69 | .tables(builderAutoConfigureProperties.getTables()) 70 | .generatorByPattern(builderAutoConfigureProperties.getGeneratorByPattern()) 71 | .ignoreClassPrefix(builderAutoConfigureProperties.getIgnoreClassPrefix()) 72 | // 项目根路径 73 | .projectBaseDir(ResourceUtils.getURL(CLASSPATH_URL_PREFIX).getPath().replace("/target/classes/", "")) 74 | .builderDir(builderAutoConfigureProperties.getBuilderDir()) 75 | .targetDir(builderAutoConfigureProperties.getTargetDir()) 76 | .builder(builderAutoConfigureProperties.getConfiguration()) 77 | .engineTypeEnum(builderAutoConfigureProperties.getEngineTypeEnum()) 78 | .build()); 79 | } catch (Exception e) { 80 | logger.error("InvokeBuilder have error :{}", e.getMessage()); 81 | } 82 | 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /code-builder-spring-boot-autoconfigure/src/main/resources/META-INF/spring-configuration-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "hints": [], 3 | "groups": [ 4 | { 5 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 6 | "name": "hengboy.code.builder", 7 | "type": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties" 8 | }, 9 | { 10 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 11 | "name": "hengboy.code.builder.configuration", 12 | "sourceMethod": "getConfiguration()", 13 | "type": "com.gitee.hengboy.builder.core.configuration.BuilderConfiguration" 14 | }, 15 | { 16 | "sourceType": "com.gitee.hengboy.builder.core.configuration.BuilderConfiguration", 17 | "name": "hengboy.code.builder.configuration.templates", 18 | "sourceMethod": "getTemplates()", 19 | "type": "com.gitee.hengboy.builder.core.configuration.TemplateConfiguration" 20 | } 21 | ], 22 | "properties": [ 23 | { 24 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 25 | "defaultValue": false, 26 | "name": "hengboy.code.builder.execute", 27 | "description": "是否执行自动生成,默认值:false(不执行)", 28 | "type": "java.lang.Boolean" 29 | }, 30 | { 31 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 32 | "name": "hengboy.code.builder.ignore-class-prefix", 33 | "description": "排除生成后实体类的前缀", 34 | "type": "java.lang.String" 35 | }, 36 | { 37 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 38 | "name": "hengboy.code.builder.generator-by-pattern", 39 | "description": "根据表达式匹配数据表进行生成", 40 | "type": "java.lang.String" 41 | }, 42 | { 43 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 44 | "name": "hengboy.code.builder.tables", 45 | "description": "根据指定表名称集合进行生成", 46 | "type": "java.util.List" 47 | }, 48 | { 49 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 50 | "name": "hengboy.code.builder.db-type", 51 | "defaultValue": "MySQL", 52 | "description": "数据库类型,默认MySQL", 53 | "type": "com.gitee.hengboy.builder.common.enums.DbTypeEnum" 54 | }, 55 | { 56 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 57 | "name": "hengboy.code.builder.engine-type-enum", 58 | "defaultValue": "FREEMARKER", 59 | "description": "驱动模板类型,默认Freemarker", 60 | "type": "com.gitee.hengboy.builder.common.enums.EngineTypeEnum" 61 | }, 62 | { 63 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 64 | "name": "hengboy.code.builder.builder-dir", 65 | "defaultValue":"target.classes.templates.builder", 66 | "description": "CodeBuilder根目录", 67 | "type": "java.lang.String" 68 | }, 69 | { 70 | "sourceType": "com.gitee.hengboy.builder.spring.boot.autoconfigure.BuilderAutoConfigureProperties", 71 | "name": "hengboy.code.builder.target-dir", 72 | "defaultValue":"target.generated-sources.java", 73 | "description": "CodeBuilder生成后实体类的根路径", 74 | "type": "java.lang.String" 75 | }, 76 | { 77 | "sourceType": "com.gitee.hengboy.builder.core.configuration.BuilderConfiguration", 78 | "name": "hengboy.code.builder.configuration.package-prefix", 79 | "description": "生成实体类的包名(package)前缀", 80 | "type": "java.lang.String" 81 | }, 82 | { 83 | "name": "hengboy.code.builder.configuration.templates", 84 | "sourceType": "com.gitee.hengboy.builder.core.configuration.BuilderConfiguration", 85 | "description": "模板列表", 86 | "type": "java.util.List" 87 | } 88 | ] 89 | } -------------------------------------------------------------------------------- /code-builder-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | #配置code-builder自动化配置 2 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 3 | com.gitee.hengboy.builder.spring.boot.autoconfigure.CodeBuilderAutoConfiguration -------------------------------------------------------------------------------- /code-builder-spring-boot-starter-sample/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | code-builder 7 | com.gitee.hengboy 8 | 1.0.5.RELEASE 9 | 10 | 4.0.0 11 | Code-Builder SpringBoot Starter示例 12 | code-builder-spring-boot-starter-sample 13 | 14 | 集成code-builder-spring-boot-starter形式 15 | 16 | 17 | 18 | 19 | 20 | 21 | com.gitee.hengboy 22 | mybatis-enhance-spring-boot-starter 23 | 1.0.3.RELEASE 24 | 25 | 26 | 27 | 28 | com.gitee.hengboy 29 | code-builder-spring-boot-starter 30 | 1.0.5.RELEASE 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | org.apache.maven.plugins 39 | maven-deploy-plugin 40 | 2.8.2 41 | 42 | true 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /code-builder-spring-boot-starter-sample/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | # spring boot starter 方式code-builder会使用项目的数据源作为读取数据库元数据的连接 3 | datasource: 4 | druid: 5 | url: jdbc:mysql://xxx.xxx.xxx.xx:3306/xxxx?characterEncoding=utf8 6 | driver-class-name: com.mysql.jdbc.Driver 7 | username: xxxxx 8 | password: xxxx 9 | 10 | # code-builder插件配置 11 | hengboy: 12 | code: 13 | builder: 14 | # true:执行生成,false:不执行生成 15 | execute: true 16 | configuration: 17 | # 生成实体类后的包名前缀 18 | package-prefix: com.code.builder.sample 19 | # 模板列表,可配置多个 20 | templates: 21 | - 22 | # entity.ftl对应resources/templates/builder/freemarker/entity.ftl 23 | name: entity.ftl 24 | # 生成后实体类的子包名 25 | packageName: model 26 | # 实体类后缀 27 | fileSuffix: Entity 28 | # 生成表达式,与like查询语法一致,优先级低于tables配置 29 | # generator-by-pattern: '%app_user_info%' 30 | 31 | # 数据库类型,默认mysql 32 | # db-type: mysql 33 | 34 | # 模板驱动类型,默认freemarker 35 | # engine-type-enum: freemarker 36 | 37 | # builder根目录,默认:classes.templates.builder 38 | # builder-dir: classes.templates.builder 39 | 40 | # 生成实体类目标位置,classes/generated-sources/java 41 | # target-dir: generated-sources.java 42 | 43 | # 指定生成的表名列表 44 | tables: 45 | - sys_menu_info 46 | - sys_role_info 47 | 48 | # 替换生成实体类后的前缀为空 49 | ignore-class-prefix: Sys 50 | 51 | -------------------------------------------------------------------------------- /code-builder-spring-boot-starter-sample/src/main/resources/templates/builder/freemarker/entity.ftl: -------------------------------------------------------------------------------- 1 | <#if (packageName)??> 2 | package ${packageName}; 3 | 4 | <#if (table.hasSqlDate)> 5 | import java.sql.Date; 6 | 7 | <#if (table.hasTimeStamp)> 8 | import java.sql.Timestamp; 9 | 10 | <#if (table.hasBigDecimal)> 11 | import java.math.BigDecimal; 12 | 13 | import com.gitee.hengboy.mybatis.enhance.common.annotation.Column; 14 | import com.gitee.hengboy.mybatis.enhance.common.annotation.Id; 15 | import com.gitee.hengboy.mybatis.enhance.common.annotation.Table; 16 | import com.gitee.hengboy.mybatis.enhance.common.enums.KeyGeneratorTypeEnum; 17 | import lombok.Data; 18 | 19 | /** 20 | *

本类由Code-Builder自动生成

21 | *

表名: ${table.tableName} - ${table.remark} - 数据实体

22 | * 23 | * @author Code-Builder 24 | * @since 恒宇少年 25 | * =============================== 26 | * Created with Code-Builder. 27 | * User: 28 | * Date:${.now} 29 | * 简书:http://www.jianshu.com/u/092df3f77bca 30 | * 码云:https://gitee.com/hengboy 31 | * GitHub:https://github.com/hengyuboy 32 | * ================================ 33 | */ 34 | @Data 35 | @Table(name = "${table.tableName}") 36 | public class ${className} { 37 | <#list table.primaryKeys as key> 38 | /** 39 | * ${key.columnName} - ${key.remark} 40 | */ 41 | <#if (key.autoincrement)> 42 | @Id(generatorType = KeyGeneratorTypeEnum.AUTO) 43 | <#else> 44 | @Id(generatorType = KeyGeneratorTypeEnum.UUID) 45 | 46 | @Column(name="${key.columnName}") 47 | private ${key.javaType} ${key.javaProperty}; 48 | 49 | <#list table.columns as column> 50 | <#if (!column.primaryKey)> 51 | /** 52 | * ${column.columnName} - ${column.remark} 53 | */ 54 | @Column(name="${column.columnName}"<#if (column.defaultValue)??>,insertable = false) 55 | private ${column.javaType} ${column.javaProperty}; 56 | 57 | 58 | } -------------------------------------------------------------------------------- /code-builder-spring-boot-starter/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | code-builder 7 | com.gitee.hengboy 8 | 1.0.5.RELEASE 9 | 10 | 4.0.0 11 | jar 12 | code-builder-spring-boot-starter 13 | 14 | 15 | 16 | 17 | com.gitee.hengboy 18 | code-builder-spring-boot-autoconfigure 19 | ${code.builder.autoconfigure.version} 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.gitee.hengboy 5 | code-builder 6 | pom 7 | 1.0.5.RELEASE 8 | 9 | code-builder-core 10 | code-builder-spring-boot-starter 11 | code-builder-spring-boot-autoconfigure 12 | code-builder-maven-plugin 13 | code-builder-maven-plugin-sample 14 | code-builder-spring-boot-starter-sample 15 | 16 | code-builder 17 | http://maven.apache.org 18 | 19 | 20 | 2.0 21 | 3.5.2 22 | 1.16.20 23 | 2.3.28 24 | 1.7.25 25 | 26 | 1.0.5.RELEASE 27 | 28 | 1.0.5.RELEASE 29 | 30 | 31 | org.springframework.boot 32 | spring-boot-starter-parent 33 | 2.0.3.RELEASE 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.projectlombok 42 | lombok 43 | ${lombok.version} 44 | provided 45 | 46 | 47 | 48 | 49 | org.freemarker 50 | freemarker 51 | ${freemarker.version} 52 | 53 | 54 | 55 | 56 | org.slf4j 57 | slf4j-api 58 | ${slf4j.version} 59 | provided 60 | 61 | 62 | 63 | 64 | 65 | Apache License, Version 2.0 66 | http://www.apache.org/licenses/LICENSE-2.0 67 | 68 | 69 | 70 | 71 | Yu Qi Yu 72 | yuqiyu@vip.qq.com 73 | https://www.jianshu.com/u/092df3f77bca 74 | gitee 75 | https://gitee.com/hengboy 76 | 77 | 78 | 79 | scm:git:https://gitee.com/hengboy/code-builder 80 | scm:git:https://gitee.com/hengboy/code-builder 81 | https://gitee.com/hengboy/code-builder 82 | 1.0.5.RELEASE 83 | 84 | 85 | 86 | hengyu 87 | https://oss.sonatype.org/content/repositories/snapshots 88 | 89 | 90 | hengyu 91 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 92 | 93 | 94 | 141 | 142 | --------------------------------------------------------------------------------