├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── settings.gradle └── src └── main ├── java └── com │ └── baomidou │ └── mybatisplus │ └── shardingjdbc │ └── spring │ └── boot │ ├── ConfigurationCustomizer.java │ ├── GlobalConfig.java │ ├── MyBatisPlusAutoConfiguration.java │ ├── MybatisPlusProperties.java │ └── SpringBootVFS.java └── resources └── META-INF ├── spring.factories └── spring.provides /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ 25 | .gradle/ 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2011-2016 hubin. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mybatis-plus 读写分离+分库分表 2 | 3 | 项目基于: https://gitee.com/baomidou/mybatisplus-sharding-jdbc 4 | 5 | 因为原项目中提到的 sharding-jdbc-mybatis-plus-spring-boot-starter 没有再更新,所以产生了此项目 6 | 7 | ### dependencies 8 | - com.baomidou:mybatis-plus:2.2.0 9 | - sharding-jdbc-core-spring-boot-starter:2.0.3 10 | - spring-boot-starter:1.5.10.RELEASE 11 | 12 | 尽量保持以上依赖跟官方最近稳定版同步 13 | 14 | 15 | ### 声明 16 | 17 | 项目 使用了 mybatis-plus 的 groupId,如果觉得不妥 可以联系我修改 18 | 19 | 20 | ### 使用 21 | 22 | ```yaml 23 | sharding.jdbc: 24 | datasource: 25 | names: ds_master_0,ds_master_0_slave_0 26 | ds_master_0: 27 | type: com.zaxxer.hikari.HikariDataSource 28 | driverClassName: com.mysql.jdbc.Driver 29 | jdbcUrl: jdbc:mysql://192.168.1.1:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf8&autoReconnect=true 30 | username: root 31 | password: 111111 32 | maxPoolSize: 20 33 | ds_master_0_slave_0: 34 | type: com.zaxxer.hikari.HikariDataSource 35 | driverClassName: com.mysql.jdbc.Driver 36 | jdbcUrl: jdbc:mysql://192.168.1.2:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf8&autoReconnect=true 37 | username: xxx 38 | password: 111111 39 | maxPoolSize: 20 40 | config: 41 | masterslave: 42 | name: ds_ms 43 | master-data-source-name: ds_master_0 44 | slave-data-source-names: ds_master_0_slave_0 45 | ``` 46 | 47 | 这里数据源根据自己需求定,详细的配置见 [Sharding-Jdbc](http://shardingjdbc.io/docs_cn/02-guide/configuration/) 48 | 49 | 50 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.baomidou' 2 | version '1.1-SNAPSHOT' 3 | 4 | apply plugin: 'java' 5 | //apply plugin: 'maven-deploy' 6 | apply plugin: 'maven-publish' 7 | apply plugin: 'propdeps' 8 | apply plugin: 'propdeps-idea' 9 | 10 | sourceCompatibility = 1.8 11 | 12 | repositories { 13 | mavenLocal() 14 | maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } 15 | maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } 16 | maven { url "http://www.cameliatk.jp/maven2/repository/thirdparty" } 17 | jcenter() 18 | } 19 | 20 | 21 | dependencies { 22 | compile "com.baomidou:mybatis-plus:2.3" 23 | compile "io.shardingjdbc:sharding-jdbc-core-spring-boot-starter:2.0.3" 24 | compile "org.springframework.boot:spring-boot-autoconfigure:1.5.10.RELEASE" 25 | compile "org.springframework.boot:spring-boot-configuration-processor:1.5.10.RELEASE" 26 | provided "org.springframework.boot:spring-boot-starter:1.5.10.RELEASE" 27 | optional "org.springframework.boot:spring-boot-starter-jdbc:1.5.10.RELEASE" 28 | testCompile group: 'junit', name: 'junit', version: '4.12' 29 | } 30 | 31 | task sourcesJar(type: Jar, dependsOn: classes) { 32 | classifier = 'sources' 33 | from sourceSets.main.allSource 34 | } 35 | 36 | 37 | artifacts { 38 | archives sourcesJar 39 | } 40 | 41 | 42 | buildscript { 43 | repositories { 44 | maven { url "https://repo.spring.io/plugins-release" } 45 | } 46 | dependencies { 47 | classpath("org.springframework.build.gradle:propdeps-plugin:0.0.7") 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | signing.keyId=1FD337F9 2 | signing.password=243194995 3 | signing.secretKeyRingFile=/Users/hubin/dev/signing.gpg 4 | local=true -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'mybatis-plus-sharding-jdbc-spring-boot-starter' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/baomidou/mybatisplus/shardingjdbc/spring/boot/ConfigurationCustomizer.java: -------------------------------------------------------------------------------- 1 | package com.baomidou.mybatisplus.shardingjdbc.spring.boot; 2 | 3 | import org.apache.ibatis.session.Configuration; 4 | 5 | /** 6 | * Callback interface that can be customized a {@link Configuration} object generated on auto-configuration. 7 | * 8 | * @author Kazuki Shimizu 9 | * @since 1.2.1 10 | */ 11 | public interface ConfigurationCustomizer { 12 | 13 | /** 14 | * Customize the given a {@link Configuration} object. 15 | * 16 | * @param configuration the configuration object to customize 17 | */ 18 | void customize(Configuration configuration); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/baomidou/mybatisplus/shardingjdbc/spring/boot/GlobalConfig.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2011-2014, hubin (jobob@qq.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 | * use this file except in compliance with the License. You may obtain a copy of 6 | * 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, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 | * License for the specific language governing permissions and limitations under 14 | * the License. 15 | */ 16 | package com.baomidou.mybatisplus.shardingjdbc.spring.boot; 17 | 18 | import com.baomidou.mybatisplus.entity.GlobalConfiguration; 19 | import com.baomidou.mybatisplus.incrementer.IKeyGenerator; 20 | import com.baomidou.mybatisplus.mapper.ISqlInjector; 21 | import com.baomidou.mybatisplus.mapper.MetaObjectHandler; 22 | import com.baomidou.mybatisplus.toolkit.StringUtils; 23 | 24 | /** 25 | *

26 | * Mybatis全局缓存 27 | *

28 | * 29 | * @author Caratacus 30 | * @since 2017-05-01 31 | */ 32 | public class GlobalConfig { 33 | 34 | /** 35 | * 主键类型 36 | */ 37 | private Integer idType; 38 | /** 39 | * 表名、字段名、是否使用下划线命名 40 | */ 41 | private Boolean dbColumnUnderline; 42 | /** 43 | * SQL注入器 44 | */ 45 | @Deprecated 46 | private String sqlInjector; 47 | /** 48 | * 元对象字段填充控制器 49 | */ 50 | @Deprecated 51 | private String metaObjectHandler; 52 | /** 53 | * 字段验证策略 54 | */ 55 | private Integer fieldStrategy; 56 | /** 57 | * 方便调试 58 | */ 59 | private Boolean refreshMapper; 60 | /** 61 | * 是否大写命名 62 | */ 63 | private Boolean isCapitalMode; 64 | /** 65 | * 标识符 66 | */ 67 | private String identifierQuote; 68 | /** 69 | * 逻辑删除全局值 70 | */ 71 | private String logicDeleteValue = null; 72 | /** 73 | * 逻辑未删除全局值 74 | */ 75 | private String logicNotDeleteValue = null; 76 | /** 77 | * 表关键词 key 生成器 78 | */ 79 | @Deprecated 80 | private String keyGenerator; 81 | /** 82 | * 缓存 Sql 解析初始化 83 | */ 84 | private Boolean sqlParserCache; 85 | 86 | public Integer getIdType() { 87 | return idType; 88 | } 89 | 90 | public void setIdType(Integer idType) { 91 | this.idType = idType; 92 | } 93 | 94 | public Boolean getDbColumnUnderline() { 95 | return dbColumnUnderline; 96 | } 97 | 98 | public void setDbColumnUnderline(Boolean dbColumnUnderline) { 99 | this.dbColumnUnderline = dbColumnUnderline; 100 | } 101 | 102 | public String getSqlInjector() { 103 | return sqlInjector; 104 | } 105 | 106 | public void setSqlInjector(String sqlInjector) { 107 | this.sqlInjector = sqlInjector; 108 | } 109 | 110 | public String getMetaObjectHandler() { 111 | return metaObjectHandler; 112 | } 113 | 114 | public void setMetaObjectHandler(String metaObjectHandler) { 115 | this.metaObjectHandler = metaObjectHandler; 116 | } 117 | 118 | public Integer getFieldStrategy() { 119 | return fieldStrategy; 120 | } 121 | 122 | public void setFieldStrategy(Integer fieldStrategy) { 123 | this.fieldStrategy = fieldStrategy; 124 | } 125 | 126 | public Boolean getCapitalMode() { 127 | return isCapitalMode; 128 | } 129 | 130 | public void setCapitalMode(Boolean capitalMode) { 131 | isCapitalMode = capitalMode; 132 | } 133 | 134 | public String getIdentifierQuote() { 135 | return identifierQuote; 136 | } 137 | 138 | public void setIdentifierQuote(String identifierQuote) { 139 | this.identifierQuote = identifierQuote; 140 | } 141 | 142 | public Boolean getRefreshMapper() { 143 | return refreshMapper; 144 | } 145 | 146 | public void setRefreshMapper(Boolean refreshMapper) { 147 | this.refreshMapper = refreshMapper; 148 | } 149 | 150 | public String getLogicDeleteValue() { 151 | return logicDeleteValue; 152 | } 153 | 154 | public void setLogicDeleteValue(String logicDeleteValue) { 155 | this.logicDeleteValue = logicDeleteValue; 156 | } 157 | 158 | public String getLogicNotDeleteValue() { 159 | return logicNotDeleteValue; 160 | } 161 | 162 | public void setLogicNotDeleteValue(String logicNotDeleteValue) { 163 | this.logicNotDeleteValue = logicNotDeleteValue; 164 | } 165 | 166 | public String getKeyGenerator() { 167 | return keyGenerator; 168 | } 169 | 170 | public void setKeyGenerator(String keyGenerator) { 171 | this.keyGenerator = keyGenerator; 172 | } 173 | 174 | public Boolean getSqlParserCache() { 175 | return sqlParserCache; 176 | } 177 | 178 | public void setSqlParserCache(Boolean sqlParserCache) { 179 | this.sqlParserCache = sqlParserCache; 180 | } 181 | 182 | public GlobalConfiguration convertGlobalConfiguration() throws ClassNotFoundException, IllegalAccessException, InstantiationException { 183 | GlobalConfiguration globalConfiguration = new GlobalConfiguration(); 184 | if (StringUtils.isNotEmpty(this.getIdentifierQuote())) { 185 | globalConfiguration.setIdentifierQuote(this.getIdentifierQuote()); 186 | } 187 | if (StringUtils.isNotEmpty(this.getLogicDeleteValue())) { 188 | globalConfiguration.setLogicDeleteValue(this.getLogicDeleteValue()); 189 | } 190 | if (StringUtils.isNotEmpty(this.getLogicNotDeleteValue())) { 191 | globalConfiguration.setLogicNotDeleteValue(this.getLogicNotDeleteValue()); 192 | } 193 | if (StringUtils.isNotEmpty(this.getSqlInjector())) { 194 | globalConfiguration.setSqlInjector((ISqlInjector) Class.forName(this.getSqlInjector()).newInstance()); 195 | } 196 | if (StringUtils.isNotEmpty(this.getMetaObjectHandler())) { 197 | globalConfiguration.setMetaObjectHandler((MetaObjectHandler) Class.forName(this.getMetaObjectHandler()).newInstance()); 198 | } 199 | if (StringUtils.isNotEmpty(this.getKeyGenerator())) { 200 | globalConfiguration.setKeyGenerator((IKeyGenerator) Class.forName(this.getKeyGenerator()).newInstance()); 201 | } 202 | if (StringUtils.checkValNotNull(this.getIdType())) { 203 | globalConfiguration.setIdType(this.getIdType()); 204 | } 205 | if (null != this.getDbColumnUnderline()) { 206 | globalConfiguration.setDbColumnUnderline(this.getDbColumnUnderline()); 207 | } 208 | if (StringUtils.checkValNotNull(this.getFieldStrategy())) { 209 | globalConfiguration.setFieldStrategy(this.getFieldStrategy()); 210 | } 211 | if (StringUtils.checkValNotNull(this.getRefreshMapper())) { 212 | globalConfiguration.setRefresh(this.getRefreshMapper()); 213 | } 214 | if (StringUtils.checkValNotNull(this.getCapitalMode())) { 215 | globalConfiguration.setCapitalMode(this.getCapitalMode()); 216 | } 217 | if (null != this.getSqlParserCache()) { 218 | globalConfiguration.setSqlParserCache(this.getSqlParserCache()); 219 | } 220 | return globalConfiguration; 221 | } 222 | 223 | } 224 | -------------------------------------------------------------------------------- /src/main/java/com/baomidou/mybatisplus/shardingjdbc/spring/boot/MyBatisPlusAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package com.baomidou.mybatisplus.shardingjdbc.spring.boot; 5 | 6 | import com.baomidou.mybatisplus.MybatisConfiguration; 7 | import com.baomidou.mybatisplus.MybatisXMLLanguageDriver; 8 | import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean; 9 | import io.shardingjdbc.spring.boot.SpringBootConfiguration; 10 | import org.apache.ibatis.annotations.Mapper; 11 | import org.apache.ibatis.logging.Log; 12 | import org.apache.ibatis.logging.LogFactory; 13 | import org.apache.ibatis.mapping.DatabaseIdProvider; 14 | import org.apache.ibatis.plugin.Interceptor; 15 | import org.apache.ibatis.session.ExecutorType; 16 | import org.apache.ibatis.session.SqlSessionFactory; 17 | import org.mybatis.spring.SqlSessionTemplate; 18 | import org.mybatis.spring.mapper.ClassPathMapperScanner; 19 | import org.mybatis.spring.mapper.MapperFactoryBean; 20 | import org.springframework.beans.BeansException; 21 | import org.springframework.beans.factory.BeanFactory; 22 | import org.springframework.beans.factory.BeanFactoryAware; 23 | import org.springframework.beans.factory.ObjectProvider; 24 | import org.springframework.beans.factory.support.BeanDefinitionRegistry; 25 | import org.springframework.boot.autoconfigure.AutoConfigurationPackages; 26 | import org.springframework.boot.autoconfigure.AutoConfigureAfter; 27 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 28 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 29 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 30 | import org.springframework.context.ResourceLoaderAware; 31 | import org.springframework.context.annotation.Bean; 32 | import org.springframework.context.annotation.Configuration; 33 | import org.springframework.context.annotation.Import; 34 | import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; 35 | import org.springframework.core.io.Resource; 36 | import org.springframework.core.io.ResourceLoader; 37 | import org.springframework.core.type.AnnotationMetadata; 38 | import org.springframework.util.Assert; 39 | import org.springframework.util.CollectionUtils; 40 | import org.springframework.util.ObjectUtils; 41 | import org.springframework.util.StringUtils; 42 | 43 | import javax.annotation.PostConstruct; 44 | import javax.sql.DataSource; 45 | import java.util.List; 46 | 47 | 48 | /** 49 | * @author junchen 50 | */ 51 | @Configuration 52 | @ConditionalOnBean(DataSource.class) 53 | @EnableConfigurationProperties(MybatisPlusProperties.class) 54 | @AutoConfigureAfter(SpringBootConfiguration.class) 55 | public class MyBatisPlusAutoConfiguration { 56 | private static final Log logger = LogFactory.getLog(MyBatisPlusAutoConfiguration.class); 57 | 58 | private final MybatisPlusProperties properties; 59 | 60 | private final Interceptor[] interceptors; 61 | 62 | private final ResourceLoader resourceLoader; 63 | 64 | private final DatabaseIdProvider databaseIdProvider; 65 | 66 | private final List configurationCustomizers; 67 | 68 | public MyBatisPlusAutoConfiguration(MybatisPlusProperties properties, 69 | ObjectProvider interceptorsProvider, 70 | ResourceLoader resourceLoader, 71 | ObjectProvider databaseIdProvider, 72 | ObjectProvider> configurationCustomizersProvider) { 73 | this.properties = properties; 74 | this.interceptors = interceptorsProvider.getIfAvailable(); 75 | this.resourceLoader = resourceLoader; 76 | this.databaseIdProvider = databaseIdProvider.getIfAvailable(); 77 | this.configurationCustomizers = configurationCustomizersProvider.getIfAvailable(); 78 | } 79 | 80 | @PostConstruct 81 | public void checkConfigFileExists() { 82 | if (this.properties.isCheckConfigLocation() && StringUtils.hasText(this.properties.getConfigLocation())) { 83 | Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation()); 84 | Assert.state(resource.exists(), "Cannot find config location: " + resource 85 | + " (please add config file or check your Mybatis configuration)"); 86 | } 87 | } 88 | 89 | @Bean 90 | @ConditionalOnMissingBean 91 | public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { 92 | MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean(); 93 | try { 94 | factory.setDataSource(dataSource); 95 | } catch (Exception e) { 96 | logger.error("DataSource:{}", e); 97 | } 98 | 99 | factory.setVfs(SpringBootVFS.class); 100 | if (StringUtils.hasText(this.properties.getConfigLocation())) { 101 | factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation())); 102 | } 103 | MybatisConfiguration configuration = this.properties.getConfiguration(); 104 | if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) { 105 | configuration = new MybatisConfiguration(); 106 | } 107 | if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) { 108 | for (ConfigurationCustomizer customizer : this.configurationCustomizers) { 109 | customizer.customize(configuration); 110 | } 111 | } 112 | configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class); 113 | factory.setConfiguration(configuration); 114 | if (this.properties.getConfigurationProperties() != null) { 115 | factory.setConfigurationProperties(this.properties.getConfigurationProperties()); 116 | } 117 | if (!ObjectUtils.isEmpty(this.interceptors)) { 118 | factory.setPlugins(this.interceptors); 119 | } 120 | if (this.databaseIdProvider != null) { 121 | factory.setDatabaseIdProvider(this.databaseIdProvider); 122 | } 123 | if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) { 124 | factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage()); 125 | } 126 | // TODO 自定义枚举包 127 | if (StringUtils.hasLength(this.properties.getTypeEnumsPackage())) { 128 | factory.setTypeEnumsPackage(this.properties.getTypeEnumsPackage()); 129 | } 130 | if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) { 131 | factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage()); 132 | } 133 | if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) { 134 | factory.setMapperLocations(this.properties.resolveMapperLocations()); 135 | } 136 | if (!ObjectUtils.isEmpty(this.properties.getGlobalConfig())) { 137 | factory.setGlobalConfig(this.properties.getGlobalConfig().convertGlobalConfiguration()); 138 | } 139 | return factory.getObject(); 140 | } 141 | 142 | @Bean 143 | @ConditionalOnMissingBean 144 | public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) { 145 | ExecutorType executorType = this.properties.getExecutorType(); 146 | if (executorType != null) { 147 | return new SqlSessionTemplate(sqlSessionFactory, executorType); 148 | } else { 149 | return new SqlSessionTemplate(sqlSessionFactory); 150 | } 151 | } 152 | 153 | /** 154 | * This will just scan the same base package as Spring Boot does. If you want 155 | * more power, you can explicitly use 156 | * {@link org.mybatis.spring.annotation.MapperScan} but this will get typed 157 | * mappers working correctly, out-of-the-box, similar to using Spring Data JPA 158 | * repositories. 159 | */ 160 | public static class AutoConfiguredMapperScannerRegistrar 161 | implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware { 162 | 163 | private BeanFactory beanFactory; 164 | 165 | private ResourceLoader resourceLoader; 166 | 167 | @Override 168 | public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { 169 | 170 | logger.debug("Searching for mappers annotated with @Mapper"); 171 | 172 | ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry); 173 | 174 | try { 175 | if (this.resourceLoader != null) { 176 | scanner.setResourceLoader(this.resourceLoader); 177 | } 178 | 179 | List packages = AutoConfigurationPackages.get(this.beanFactory); 180 | if (logger.isDebugEnabled()) { 181 | for (String pkg : packages) { 182 | logger.debug("Using auto-configuration base package '" + pkg + "'"); 183 | } 184 | } 185 | 186 | scanner.setAnnotationClass(Mapper.class); 187 | scanner.registerFilters(); 188 | scanner.doScan(StringUtils.toStringArray(packages)); 189 | } catch (IllegalStateException ex) { 190 | logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled." + ex); 191 | } 192 | } 193 | 194 | @Override 195 | public void setBeanFactory(BeanFactory beanFactory) throws BeansException { 196 | this.beanFactory = beanFactory; 197 | } 198 | 199 | @Override 200 | public void setResourceLoader(ResourceLoader resourceLoader) { 201 | this.resourceLoader = resourceLoader; 202 | } 203 | } 204 | 205 | /** 206 | * {@link org.mybatis.spring.annotation.MapperScan} ultimately ends up 207 | * creating instances of {@link MapperFactoryBean}. If 208 | * {@link org.mybatis.spring.annotation.MapperScan} is used then this 209 | * auto-configuration is not needed. If it is _not_ used, however, then this 210 | * will bring in a bean registrar and automatically register components based 211 | * on the same component-scanning path as Spring Boot itself. 212 | */ 213 | @org.springframework.context.annotation.Configuration 214 | @Import({AutoConfiguredMapperScannerRegistrar.class}) 215 | @ConditionalOnMissingBean(MapperFactoryBean.class) 216 | public static class MapperScannerRegistrarNotFoundConfiguration { 217 | 218 | @PostConstruct 219 | public void afterPropertiesSet() { 220 | logger.debug("No " + MapperFactoryBean.class.getName() + " found."); 221 | } 222 | } 223 | 224 | } 225 | -------------------------------------------------------------------------------- /src/main/java/com/baomidou/mybatisplus/shardingjdbc/spring/boot/MybatisPlusProperties.java: -------------------------------------------------------------------------------- 1 | package com.baomidou.mybatisplus.shardingjdbc.spring.boot; 2 | 3 | import com.baomidou.mybatisplus.MybatisConfiguration; 4 | import org.apache.ibatis.session.ExecutorType; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import org.springframework.boot.context.properties.NestedConfigurationProperty; 7 | import org.springframework.core.io.Resource; 8 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 9 | import org.springframework.core.io.support.ResourcePatternResolver; 10 | 11 | import java.io.IOException; 12 | import java.util.ArrayList; 13 | import java.util.Arrays; 14 | import java.util.List; 15 | import java.util.Properties; 16 | 17 | /** 18 | * Configuration properties for MyBatis. 19 | * 20 | * @author Eddú Meléndez 21 | * @author Kazuki Shimizu 22 | */ 23 | @ConfigurationProperties(prefix = MybatisPlusProperties.MYBATIS_PLUS_PREFIX) 24 | public class MybatisPlusProperties { 25 | 26 | public static final String MYBATIS_PLUS_PREFIX = "mybatis-plus"; 27 | 28 | /** 29 | * Location of MyBatis xml config file. 30 | */ 31 | private String configLocation; 32 | 33 | /** 34 | * Locations of MyBatis mapper files. 35 | */ 36 | private String[] mapperLocations; 37 | 38 | /** 39 | * Packages to search type aliases. (Package delimiters are ",; \t\n") 40 | */ 41 | private String typeAliasesPackage; 42 | 43 | // TODO 自定义枚举包 44 | private String typeEnumsPackage; 45 | 46 | /** 47 | * Packages to search for type handlers. (Package delimiters are ",; \t\n") 48 | */ 49 | private String typeHandlersPackage; 50 | 51 | /** 52 | * Indicates whether perform presence check of the MyBatis xml config file. 53 | */ 54 | private boolean checkConfigLocation = false; 55 | 56 | /** 57 | * Execution mode for {@link org.mybatis.spring.SqlSessionTemplate}. 58 | */ 59 | private ExecutorType executorType; 60 | 61 | /** 62 | * Externalized properties for MyBatis configuration. 63 | */ 64 | private Properties configurationProperties; 65 | /** 66 | * Externalized properties for MyBatis configuration. 67 | */ 68 | @NestedConfigurationProperty 69 | private GlobalConfig globalConfig; 70 | 71 | /** 72 | * A Configuration object for customize default settings. If {@link #configLocation} 73 | * is specified, this property is not used. 74 | */ 75 | @NestedConfigurationProperty 76 | private MybatisConfiguration configuration; 77 | 78 | /** 79 | * @since 1.1.0 80 | */ 81 | public String getConfigLocation() { 82 | return this.configLocation; 83 | } 84 | 85 | /** 86 | * @since 1.1.0 87 | */ 88 | public void setConfigLocation(String configLocation) { 89 | this.configLocation = configLocation; 90 | } 91 | 92 | public String[] getMapperLocations() { 93 | return this.mapperLocations; 94 | } 95 | 96 | public void setMapperLocations(String[] mapperLocations) { 97 | this.mapperLocations = mapperLocations; 98 | } 99 | 100 | public String getTypeHandlersPackage() { 101 | return this.typeHandlersPackage; 102 | } 103 | 104 | public void setTypeHandlersPackage(String typeHandlersPackage) { 105 | this.typeHandlersPackage = typeHandlersPackage; 106 | } 107 | 108 | public String getTypeAliasesPackage() { 109 | return this.typeAliasesPackage; 110 | } 111 | 112 | public void setTypeAliasesPackage(String typeAliasesPackage) { 113 | this.typeAliasesPackage = typeAliasesPackage; 114 | } 115 | 116 | public String getTypeEnumsPackage() { 117 | return typeEnumsPackage; 118 | } 119 | 120 | public void setTypeEnumsPackage(String typeEnumsPackage) { 121 | this.typeEnumsPackage = typeEnumsPackage; 122 | } 123 | 124 | public boolean isCheckConfigLocation() { 125 | return this.checkConfigLocation; 126 | } 127 | 128 | public void setCheckConfigLocation(boolean checkConfigLocation) { 129 | this.checkConfigLocation = checkConfigLocation; 130 | } 131 | 132 | public ExecutorType getExecutorType() { 133 | return this.executorType; 134 | } 135 | 136 | public void setExecutorType(ExecutorType executorType) { 137 | this.executorType = executorType; 138 | } 139 | 140 | /** 141 | * @since 1.2.0 142 | */ 143 | public Properties getConfigurationProperties() { 144 | return configurationProperties; 145 | } 146 | 147 | /** 148 | * @since 1.2.0 149 | */ 150 | public void setConfigurationProperties(Properties configurationProperties) { 151 | this.configurationProperties = configurationProperties; 152 | } 153 | 154 | public MybatisConfiguration getConfiguration() { 155 | return configuration; 156 | } 157 | 158 | public void setConfiguration(MybatisConfiguration configuration) { 159 | this.configuration = configuration; 160 | } 161 | 162 | public Resource[] resolveMapperLocations() { 163 | ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); 164 | List resources = new ArrayList(); 165 | if (this.mapperLocations != null) { 166 | for (String mapperLocation : this.mapperLocations) { 167 | try { 168 | Resource[] mappers = resourceResolver.getResources(mapperLocation); 169 | resources.addAll(Arrays.asList(mappers)); 170 | } catch (IOException e) { 171 | // ignore 172 | } 173 | } 174 | } 175 | return resources.toArray(new Resource[resources.size()]); 176 | } 177 | 178 | public GlobalConfig getGlobalConfig() { 179 | return globalConfig; 180 | } 181 | 182 | public void setGlobalConfig(GlobalConfig globalConfig) { 183 | this.globalConfig = globalConfig; 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /src/main/java/com/baomidou/mybatisplus/shardingjdbc/spring/boot/SpringBootVFS.java: -------------------------------------------------------------------------------- 1 | package com.baomidou.mybatisplus.shardingjdbc.spring.boot; 2 | 3 | import org.apache.ibatis.io.VFS; 4 | import org.springframework.core.io.Resource; 5 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 6 | import org.springframework.core.io.support.ResourcePatternResolver; 7 | 8 | import java.io.IOException; 9 | import java.net.URI; 10 | import java.net.URL; 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | /** 15 | * @author Hans Westerbeek 16 | * @author Eddú Meléndez 17 | * @author Kazuki Shimizu 18 | */ 19 | public class SpringBootVFS extends VFS { 20 | 21 | private final ResourcePatternResolver resourceResolver; 22 | 23 | public SpringBootVFS() { 24 | this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); 25 | } 26 | 27 | private static String preserveSubpackageName(final URI uri, final String rootPath) { 28 | final String uriStr = uri.toString(); 29 | final int start = uriStr.indexOf(rootPath); 30 | return uriStr.substring(start); 31 | } 32 | 33 | @Override 34 | public boolean isValid() { 35 | return true; 36 | } 37 | 38 | @Override 39 | protected List list(URL url, String path) throws IOException { 40 | Resource[] resources = resourceResolver.getResources("classpath*:" + path + "/**/*.class"); 41 | List resourcePaths = new ArrayList(); 42 | for (Resource resource : resources) { 43 | resourcePaths.add(preserveSubpackageName(resource.getURI(), path)); 44 | } 45 | return resourcePaths; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | com.baomidou.mybatisplus.shardingjdbc.spring.boot.MyBatisPlusAutoConfiguration 3 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring.provides: -------------------------------------------------------------------------------- 1 | provides: mybatis-plus-sharding-jdbc-spring-boot-starter 2 | --------------------------------------------------------------------------------