├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src └── main ├── java └── com │ └── huan │ ├── Application.java │ ├── config │ ├── AbstractApplication.java │ ├── DataSourceAspect.java │ └── MyBatisConfig.java │ ├── controller │ ├── TestDataSourceController.java │ └── WelcomeController.java │ ├── mapper │ ├── UserDetailMapper.java │ └── UserInfoMapper.java │ ├── model │ ├── UserDetail.java │ └── UserInfo.java │ ├── service │ ├── CommonService.java │ ├── Test1Service.java │ ├── Test2Service.java │ └── impl │ │ ├── CommonServiceImpl.java │ │ ├── Test1ServiceImpl.java │ │ └── Test2ServiceImpl.java │ └── util │ ├── Constants.java │ ├── DatabaseContextHolder.java │ ├── DatabaseType.java │ └── DynamicDataSource.java └── resources ├── application.yml ├── database1.sql ├── database2.sql ├── generator ├── generatorConfig.xml └── mybatis_generator_config.properties ├── logback.xml └── mapper ├── UserDetailMapper.xml └── UserInfoMapper.xml /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | .idea/ 11 | target/ 12 | *.iml 13 | 14 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 15 | hs_err_pid* 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # springboot-multiple-dataSources 2 | 3 | ### 前言 ### 4 | 5 | spring-boot多数据源自动切换例子项目, 利用spring aop 切面,自动切换数据源。 6 | 7 | CommonServiceImpl是公共处理类,Test1ServiceImpl和Test2ServiceImpl是两个数据源分别的业务处理类。定义DataSourceAspect类处理切面。 8 | 9 | springboot-multiple-dataSources/src/main/resources目录下的database1.sql和database2.sql是2个数据源初始化脚本 10 | 11 | ### 软件环境 ### 12 | IntelliJ IDEA 2016.3.3(或eclipse) 13 | 14 | jdk 1.8 15 | 16 | maven 3.3.9 17 | 18 | ### 使用的技术 ### 19 | 20 | - spring-boot 21 | - springmvc 22 | - mybatis 23 | - 通用mapper(一个非常好用的mybatis插件, 详细介绍见http://git.oschina.net/free/Mapper) 24 | 25 | ### 在IDE 中查看源码并运行 ### 26 | 27 | **1. 在IntelliJ IDEA (推荐使用)** 28 | 29 | File -> Import Project -> select springboot-multiple-dataSources folder -> create project form existing sources -> ... 30 | 31 | **2. 在Eclipse** 32 | 33 | File -> Import -> Existing Maven Projects -> ... 34 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.huan 8 | springboot-multiple-dataSources 9 | 1.0-SNAPSHOT 10 | war 11 | 12 | 13 | UTF-8 14 | 15 | 16 | ${basedir}/src/main/java 17 | com.huan.mapper 18 | com.huan.model 19 | 20 | ${basedir}/src/main/resources 21 | mapper 22 | 5.1.42 23 | 4.12 24 | 3.4.0 25 | 4.1.6 26 | 1.1.7 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-parent 32 | 1.5.2.RELEASE 33 | 34 | 35 | 36 | 37 | junit 38 | junit 39 | ${junit.version} 40 | test 41 | 42 | 43 | org.slf4j 44 | slf4j-api 45 | 1.7.21 46 | 47 | 48 | 49 | ch.qos.logback 50 | logback-classic 51 | ${logback.version} 52 | 53 | 54 | ch.qos.logback 55 | logback-core 56 | ${logback.version} 57 | 58 | 59 | javax.servlet 60 | javax.servlet-api 61 | 3.1.0 62 | provided 63 | 64 | 65 | 66 | 67 | org.springframework.boot 68 | spring-boot-starter-web 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-starter-data-jpa 73 | 74 | 75 | org.springframework.boot 76 | spring-boot-starter-freemarker 77 | 78 | 79 | 80 | mysql 81 | mysql-connector-java 82 | ${mysql.version} 83 | 84 | 85 | 86 | com.alibaba 87 | druid 88 | 1.0.31 89 | 90 | 91 | 92 | 93 | org.mybatis 94 | mybatis 95 | 3.4.4 96 | 97 | 98 | org.mybatis 99 | mybatis-spring 100 | 1.3.1 101 | 102 | 103 | 104 | org.mybatis.generator 105 | mybatis-generator-core 106 | 1.3.5 107 | compile 108 | true 109 | 110 | 111 | 112 | tk.mybatis 113 | mapper 114 | ${mapper.version} 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | ${basedir}/src/main/java 123 | 124 | **/*.xml 125 | 126 | 127 | 128 | ${basedir}/src/main/resources 129 | 130 | 131 | 132 | 133 | org.mybatis.generator 134 | mybatis-generator-maven-plugin 135 | 1.3.5 136 | 137 | ${basedir}/src/main/resources/generator/generatorConfig.xml 138 | true 139 | true 140 | 141 | 142 | 143 | mysql 144 | mysql-connector-java 145 | ${mysql.version} 146 | 147 | 148 | tk.mybatis 149 | mapper 150 | ${mapper.version} 151 | 152 | 153 | 154 | 155 | org.springframework.boot 156 | spring-boot-maven-plugin 157 | 158 | true 159 | 160 | 161 | 162 | org.apache.maven.plugins 163 | maven-compiler-plugin 164 | 3.5.1 165 | 166 | 1.8 167 | 1.8 168 | UTF-8 169 | 170 | 171 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /src/main/java/com/huan/Application.java: -------------------------------------------------------------------------------- 1 | package com.huan; 2 | 3 | import com.huan.config.AbstractApplication; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 7 | 8 | import java.net.UnknownHostException; 9 | 10 | @SpringBootApplication(scanBasePackages = "com.huan", exclude = {DataSourceAutoConfiguration.class}) 11 | public class Application extends AbstractApplication { 12 | 13 | public static void main(String[] args) throws UnknownHostException { 14 | SpringApplication app = new SpringApplication(Application.class); 15 | app.run(args); 16 | // abstractMain(app, args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/huan/config/AbstractApplication.java: -------------------------------------------------------------------------------- 1 | package com.huan.config; 2 | 3 | import com.huan.util.Constants; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.builder.SpringApplicationBuilder; 9 | import org.springframework.boot.web.support.SpringBootServletInitializer; 10 | import org.springframework.core.env.ConfigurableEnvironment; 11 | import org.springframework.core.env.Environment; 12 | import org.springframework.core.env.SimpleCommandLinePropertySource; 13 | 14 | import javax.annotation.PostConstruct; 15 | import java.io.IOException; 16 | import java.net.InetAddress; 17 | import java.net.UnknownHostException; 18 | import java.util.Arrays; 19 | import java.util.Collection; 20 | 21 | /** 22 | * @author Jean Seurin 23 | * @since 12/11/15 - 10:16 24 | */ 25 | public class AbstractApplication extends SpringBootServletInitializer { 26 | 27 | protected static final Logger logger = LoggerFactory.getLogger(AbstractApplication.class); 28 | protected static Environment staticEnv; 29 | @Autowired 30 | protected ConfigurableEnvironment env; 31 | 32 | protected static void abstractMain(SpringApplication app, String[] args) throws UnknownHostException { 33 | SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); 34 | addDefaultProfile(app, source); 35 | //addLiquibaseScanPackages(); 36 | staticEnv = app.run(args).getEnvironment(); 37 | showAppInfo(staticEnv); 38 | } 39 | 40 | protected static void showAppInfo(final Environment env) throws UnknownHostException { 41 | String isSslEnabled = env.getProperty("server.ssl.enabled"); 42 | String protocol = "http"; 43 | if (isSslEnabled != null && "true".equals(isSslEnabled)) { 44 | protocol = "https"; 45 | } 46 | logger.info("Access URLs:\n----------------------------------------------------------\n\t" + 47 | "Local: \t\t" + protocol + "://127.0.0.1:{}\n\t" + 48 | "External: \t" + protocol + "://{}:{}\n----------------------------------------------------------", 49 | env.getProperty("server.port"), 50 | InetAddress.getLocalHost().getHostAddress(), 51 | env.getProperty("server.port")); 52 | } 53 | 54 | /** 55 | * If no profile has been configured, set by default the "dev" profile. 56 | */ 57 | protected static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { 58 | if ((System.getProperty("spring.profiles.active") == null) 59 | && !source.containsProperty("spring.profiles.active") 60 | && !System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) { 61 | app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT); 62 | } 63 | } 64 | 65 | @Override 66 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 67 | return application.sources(this.getClass()); 68 | } 69 | 70 | /** 71 | * Initializes the application. Do some checks on profile configuration 72 | *

73 | * Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile 74 | *

75 | */ 76 | @PostConstruct 77 | public void initApplication() throws IOException { 78 | if (env.getActiveProfiles().length == 0) { 79 | logger.warn("No Spring profile configured, running with default configuration"); 80 | } else { 81 | logger.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles())); 82 | Collection activeProfiles = Arrays.asList(env.getActiveProfiles()); 83 | if (activeProfiles.contains("dev") && activeProfiles.contains("prod")) { 84 | logger.error("You have misconfigured your application! It should not run with both the 'dev' and 'prod' profiles at the same time."); 85 | } 86 | if (activeProfiles.contains("prod") && activeProfiles.contains("fast")) { 87 | logger.error("You have misconfigured your application! It should not run with both the 'prod' and 'fast' profiles at the same time."); 88 | } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/huan/config/DataSourceAspect.java: -------------------------------------------------------------------------------- 1 | package com.huan.config; 2 | 3 | import com.huan.service.Test1Service; 4 | import com.huan.service.impl.Test1ServiceImpl; 5 | import com.huan.util.DatabaseContextHolder; 6 | import com.huan.util.DatabaseType; 7 | import org.aspectj.lang.JoinPoint; 8 | import org.aspectj.lang.annotation.Aspect; 9 | import org.aspectj.lang.annotation.Before; 10 | import org.aspectj.lang.annotation.Pointcut; 11 | import org.springframework.stereotype.Component; 12 | 13 | @Aspect 14 | @Component 15 | public class DataSourceAspect { 16 | 17 | /** 18 | * 使用空方法定义切点表达式 19 | */ 20 | @Pointcut("execution(* com.huan.service.**.*(..))") 21 | public void declareJointPointExpression() { 22 | } 23 | 24 | @Before("declareJointPointExpression()") 25 | public void setDataSourceKey(JoinPoint point){ 26 | //根据连接点所属的类实例,动态切换数据源 27 | if (point.getTarget() instanceof Test1Service 28 | || point.getTarget() instanceof Test1ServiceImpl) { 29 | DatabaseContextHolder.setDatabaseType(DatabaseType.test1); 30 | } else {//连接点所属的类实例是(当然,这一步也可以不写,因为defaultTargertDataSource就是该类所用的mytestdb) 31 | DatabaseContextHolder.setDatabaseType(DatabaseType.test2); 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/config/MyBatisConfig.java: -------------------------------------------------------------------------------- 1 | package com.huan.config; 2 | 3 | import com.alibaba.druid.pool.DruidDataSourceFactory; 4 | import com.huan.util.DatabaseType; 5 | import com.huan.util.DynamicDataSource; 6 | import org.apache.ibatis.session.SqlSessionFactory; 7 | import org.mybatis.spring.SqlSessionFactoryBean; 8 | import org.springframework.beans.factory.annotation.Qualifier; 9 | import org.springframework.context.EnvironmentAware; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.context.annotation.Primary; 13 | import org.springframework.core.env.Environment; 14 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 15 | import org.springframework.jdbc.datasource.DataSourceTransactionManager; 16 | import tk.mybatis.spring.mapper.MapperScannerConfigurer; 17 | 18 | import javax.sql.DataSource; 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | import java.util.Properties; 22 | 23 | /** 24 | * springboot集成mybatis的基本入口 1)创建数据源(如果采用的是默认的tomcat-jdbc数据源,则不需要) 25 | * 2)创建SqlSessionFactory 3)配置事务管理器,除非需要使用事务,否则不用配置 26 | */ 27 | @Configuration // 该注解类似于spring配置文件 28 | public class MyBatisConfig implements EnvironmentAware { 29 | 30 | private Environment environment; 31 | 32 | @Override 33 | public void setEnvironment(final Environment environment) { 34 | this.environment = environment; 35 | } 36 | 37 | /** 38 | * 创建数据源(数据源的名称:方法名可以取为XXXDataSource(),XXX为数据库名称,该名称也就是数据源的名称) 39 | */ 40 | @Bean 41 | public DataSource test1DataSource() throws Exception { 42 | Properties props = new Properties(); 43 | props.put("driverClassName", environment.getProperty("test1-datasource.driverClassName")); 44 | props.put("url", environment.getProperty("test1-datasource.url")); 45 | props.put("username", environment.getProperty("test1-datasource.username")); 46 | props.put("password", environment.getProperty("test1-datasource.password")); 47 | return DruidDataSourceFactory.createDataSource(props); 48 | } 49 | 50 | @Bean 51 | public DataSource test2DataSource() throws Exception { 52 | Properties props = new Properties(); 53 | props.put("driverClassName", environment.getProperty("test2-datasource.driverClassName")); 54 | props.put("url", environment.getProperty("test2-datasource.url")); 55 | props.put("username", environment.getProperty("test2-datasource.username")); 56 | props.put("password", environment.getProperty("test2-datasource.password")); 57 | return DruidDataSourceFactory.createDataSource(props); 58 | } 59 | 60 | /** 61 | * @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错 62 | * @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例) 63 | */ 64 | @Bean 65 | @Primary 66 | public DynamicDataSource dataSource(@Qualifier("test1DataSource") DataSource test1DataSource, 67 | @Qualifier("test2DataSource") DataSource test2DataSource) { 68 | Map targetDataSources = new HashMap<>(); 69 | targetDataSources.put(DatabaseType.test1, test1DataSource); 70 | targetDataSources.put(DatabaseType.test2, test2DataSource); 71 | 72 | DynamicDataSource dataSource = new DynamicDataSource(); 73 | dataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法 74 | dataSource.setDefaultTargetDataSource(test2DataSource);// 默认的datasource设置为myTestDbDataSource 75 | 76 | return dataSource; 77 | } 78 | 79 | @Bean 80 | public MapperScannerConfigurer mapperScannerConfigurer() { 81 | MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer(); 82 | scannerConfigurer.setBasePackage("com.huan.mapper"); 83 | Properties props = new Properties(); 84 | props.setProperty("mappers", "tk.mybatis.mapper.common.Mapper"); 85 | props.setProperty("IDENTITY", "MYSQL"); 86 | props.setProperty("notEmpty", "true"); 87 | scannerConfigurer.setProperties(props); 88 | return scannerConfigurer; 89 | } 90 | 91 | /** 92 | * 根据数据源创建SqlSessionFactory 93 | */ 94 | @Bean 95 | public SqlSessionFactory sqlSessionFactory(DynamicDataSource ds) throws Exception { 96 | PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); 97 | 98 | SqlSessionFactoryBean fb = new SqlSessionFactoryBean(); 99 | fb.setDataSource(ds);// 指定数据源(这个必须有,否则报错) 100 | // 下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加 101 | fb.setTypeAliasesPackage("com.huan.model");// 指定基包 102 | fb.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml"));// 103 | 104 | return fb.getObject(); 105 | } 106 | 107 | 108 | 109 | /** 110 | * 配置事务管理器 111 | */ 112 | @Bean 113 | public DataSourceTransactionManager transactionManager(DynamicDataSource dataSource) throws Exception { 114 | return new DataSourceTransactionManager(dataSource); 115 | } 116 | 117 | 118 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/controller/TestDataSourceController.java: -------------------------------------------------------------------------------- 1 | package com.huan.controller; 2 | 3 | import com.huan.model.UserDetail; 4 | import com.huan.model.UserInfo; 5 | import com.huan.service.CommonService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RequestMethod; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.util.List; 12 | 13 | @RestController 14 | public class TestDataSourceController { 15 | 16 | @Autowired 17 | private CommonService commonService; 18 | 19 | @RequestMapping(value = "/test1", method = RequestMethod.GET) 20 | public List selectUser() { 21 | System.out.println("查询第一个数据源"); 22 | return commonService.selectUserInfo(); 23 | } 24 | 25 | @RequestMapping(value = "/test2", method = RequestMethod.GET) 26 | public List userDetail() { 27 | System.out.println("查询第二个数据源"); 28 | return commonService.selectUserDetail(); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/controller/WelcomeController.java: -------------------------------------------------------------------------------- 1 | package com.huan.controller; 2 | 3 | import org.springframework.web.bind.annotation.RequestMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | import java.util.Date; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | /** 11 | * Created by huan on 2016/5/21. 12 | */ 13 | @RestController 14 | public class WelcomeController { 15 | 16 | @RequestMapping("/") 17 | public Map welcome() { 18 | Map model = new HashMap(); 19 | model.put("time", new Date()); 20 | model.put("message", "Hello World"); 21 | return model; 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/mapper/UserDetailMapper.java: -------------------------------------------------------------------------------- 1 | package com.huan.mapper; 2 | 3 | import com.huan.model.UserDetail; 4 | import tk.mybatis.mapper.common.Mapper; 5 | 6 | public interface UserDetailMapper extends Mapper { 7 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/mapper/UserInfoMapper.java: -------------------------------------------------------------------------------- 1 | package com.huan.mapper; 2 | 3 | import com.huan.model.UserInfo; 4 | 5 | import java.util.List; 6 | 7 | public interface UserInfoMapper { 8 | /** 9 | * This method was generated by MyBatis Generator. 10 | * This method corresponds to the database table user_info 11 | * 12 | * @mbggenerated Fri May 27 01:50:31 CST 2016 13 | */ 14 | int deleteByPrimaryKey(String id); 15 | 16 | /** 17 | * This method was generated by MyBatis Generator. 18 | * This method corresponds to the database table user_info 19 | * 20 | * @mbggenerated Fri May 27 01:50:31 CST 2016 21 | */ 22 | int insert(UserInfo record); 23 | 24 | /** 25 | * This method was generated by MyBatis Generator. 26 | * This method corresponds to the database table user_info 27 | * 28 | * @mbggenerated Fri May 27 01:50:31 CST 2016 29 | */ 30 | UserInfo selectByPrimaryKey(String id); 31 | 32 | /** 33 | * This method was generated by MyBatis Generator. 34 | * This method corresponds to the database table user_info 35 | * 36 | * @mbggenerated Fri May 27 01:50:31 CST 2016 37 | */ 38 | List selectAll(); 39 | 40 | /** 41 | * This method was generated by MyBatis Generator. 42 | * This method corresponds to the database table user_info 43 | * 44 | * @mbggenerated Fri May 27 01:50:31 CST 2016 45 | */ 46 | int updateByPrimaryKey(UserInfo record); 47 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/model/UserDetail.java: -------------------------------------------------------------------------------- 1 | package com.huan.model; 2 | 3 | import javax.persistence.GeneratedValue; 4 | import javax.persistence.GenerationType; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | 8 | @Table(name = "user_detail") 9 | public class UserDetail { 10 | @Id 11 | @GeneratedValue(strategy = GenerationType.IDENTITY) 12 | private Long id; 13 | 14 | private String name; 15 | 16 | private String qq; 17 | 18 | /** 19 | * @return id 20 | */ 21 | public Long getId() { 22 | return id; 23 | } 24 | 25 | /** 26 | * @param id 27 | */ 28 | public void setId(Long id) { 29 | this.id = id; 30 | } 31 | 32 | /** 33 | * @return name 34 | */ 35 | public String getName() { 36 | return name; 37 | } 38 | 39 | /** 40 | * @param name 41 | */ 42 | public void setName(String name) { 43 | this.name = name; 44 | } 45 | 46 | /** 47 | * @return qq 48 | */ 49 | public String getQq() { 50 | return qq; 51 | } 52 | 53 | /** 54 | * @param qq 55 | */ 56 | public void setQq(String qq) { 57 | this.qq = qq; 58 | } 59 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/model/UserInfo.java: -------------------------------------------------------------------------------- 1 | package com.huan.model; 2 | 3 | public class UserInfo { 4 | /** 5 | * This field was generated by MyBatis Generator. 6 | * This field corresponds to the database column user_info.id 7 | * 8 | * @mbggenerated Fri May 27 01:50:31 CST 2016 9 | */ 10 | private String id; 11 | 12 | /** 13 | * This field was generated by MyBatis Generator. 14 | * This field corresponds to the database column user_info.username 15 | * 16 | * @mbggenerated Fri May 27 01:50:31 CST 2016 17 | */ 18 | private String username; 19 | 20 | /** 21 | * This field was generated by MyBatis Generator. 22 | * This field corresponds to the database column user_info.net_name 23 | * 24 | * @mbggenerated Fri May 27 01:50:31 CST 2016 25 | */ 26 | private String netName; 27 | 28 | /** 29 | * This field was generated by MyBatis Generator. 30 | * This field corresponds to the database column user_info.job 31 | * 32 | * @mbggenerated Fri May 27 01:50:31 CST 2016 33 | */ 34 | private String job; 35 | 36 | /** 37 | * This field was generated by MyBatis Generator. 38 | * This field corresponds to the database column user_info.family_native_place 39 | * 40 | * @mbggenerated Fri May 27 01:50:31 CST 2016 41 | */ 42 | private String familyNativePlace; 43 | 44 | /** 45 | * This field was generated by MyBatis Generator. 46 | * This field corresponds to the database column user_info.mobile 47 | * 48 | * @mbggenerated Fri May 27 01:50:31 CST 2016 49 | */ 50 | private String mobile; 51 | 52 | /** 53 | * This field was generated by MyBatis Generator. 54 | * This field corresponds to the database column user_info.email 55 | * 56 | * @mbggenerated Fri May 27 01:50:31 CST 2016 57 | */ 58 | private String email; 59 | 60 | /** 61 | * This method was generated by MyBatis Generator. 62 | * This method returns the value of the database column user_info.id 63 | * 64 | * @return the value of user_info.id 65 | * 66 | * @mbggenerated Fri May 27 01:50:31 CST 2016 67 | */ 68 | public String getId() { 69 | return id; 70 | } 71 | 72 | /** 73 | * This method was generated by MyBatis Generator. 74 | * This method sets the value of the database column user_info.id 75 | * 76 | * @param id the value for user_info.id 77 | * 78 | * @mbggenerated Fri May 27 01:50:31 CST 2016 79 | */ 80 | public void setId(String id) { 81 | this.id = id; 82 | } 83 | 84 | /** 85 | * This method was generated by MyBatis Generator. 86 | * This method returns the value of the database column user_info.username 87 | * 88 | * @return the value of user_info.username 89 | * 90 | * @mbggenerated Fri May 27 01:50:31 CST 2016 91 | */ 92 | public String getUsername() { 93 | return username; 94 | } 95 | 96 | /** 97 | * This method was generated by MyBatis Generator. 98 | * This method sets the value of the database column user_info.username 99 | * 100 | * @param username the value for user_info.username 101 | * 102 | * @mbggenerated Fri May 27 01:50:31 CST 2016 103 | */ 104 | public void setUsername(String username) { 105 | this.username = username; 106 | } 107 | 108 | /** 109 | * This method was generated by MyBatis Generator. 110 | * This method returns the value of the database column user_info.net_name 111 | * 112 | * @return the value of user_info.net_name 113 | * 114 | * @mbggenerated Fri May 27 01:50:31 CST 2016 115 | */ 116 | public String getNetName() { 117 | return netName; 118 | } 119 | 120 | /** 121 | * This method was generated by MyBatis Generator. 122 | * This method sets the value of the database column user_info.net_name 123 | * 124 | * @param netName the value for user_info.net_name 125 | * 126 | * @mbggenerated Fri May 27 01:50:31 CST 2016 127 | */ 128 | public void setNetName(String netName) { 129 | this.netName = netName; 130 | } 131 | 132 | /** 133 | * This method was generated by MyBatis Generator. 134 | * This method returns the value of the database column user_info.job 135 | * 136 | * @return the value of user_info.job 137 | * 138 | * @mbggenerated Fri May 27 01:50:31 CST 2016 139 | */ 140 | public String getJob() { 141 | return job; 142 | } 143 | 144 | /** 145 | * This method was generated by MyBatis Generator. 146 | * This method sets the value of the database column user_info.job 147 | * 148 | * @param job the value for user_info.job 149 | * 150 | * @mbggenerated Fri May 27 01:50:31 CST 2016 151 | */ 152 | public void setJob(String job) { 153 | this.job = job; 154 | } 155 | 156 | /** 157 | * This method was generated by MyBatis Generator. 158 | * This method returns the value of the database column user_info.family_native_place 159 | * 160 | * @return the value of user_info.family_native_place 161 | * 162 | * @mbggenerated Fri May 27 01:50:31 CST 2016 163 | */ 164 | public String getFamilyNativePlace() { 165 | return familyNativePlace; 166 | } 167 | 168 | /** 169 | * This method was generated by MyBatis Generator. 170 | * This method sets the value of the database column user_info.family_native_place 171 | * 172 | * @param familyNativePlace the value for user_info.family_native_place 173 | * 174 | * @mbggenerated Fri May 27 01:50:31 CST 2016 175 | */ 176 | public void setFamilyNativePlace(String familyNativePlace) { 177 | this.familyNativePlace = familyNativePlace; 178 | } 179 | 180 | /** 181 | * This method was generated by MyBatis Generator. 182 | * This method returns the value of the database column user_info.mobile 183 | * 184 | * @return the value of user_info.mobile 185 | * 186 | * @mbggenerated Fri May 27 01:50:31 CST 2016 187 | */ 188 | public String getMobile() { 189 | return mobile; 190 | } 191 | 192 | /** 193 | * This method was generated by MyBatis Generator. 194 | * This method sets the value of the database column user_info.mobile 195 | * 196 | * @param mobile the value for user_info.mobile 197 | * 198 | * @mbggenerated Fri May 27 01:50:31 CST 2016 199 | */ 200 | public void setMobile(String mobile) { 201 | this.mobile = mobile; 202 | } 203 | 204 | /** 205 | * This method was generated by MyBatis Generator. 206 | * This method returns the value of the database column user_info.email 207 | * 208 | * @return the value of user_info.email 209 | * 210 | * @mbggenerated Fri May 27 01:50:31 CST 2016 211 | */ 212 | public String getEmail() { 213 | return email; 214 | } 215 | 216 | /** 217 | * This method was generated by MyBatis Generator. 218 | * This method sets the value of the database column user_info.email 219 | * 220 | * @param email the value for user_info.email 221 | * 222 | * @mbggenerated Fri May 27 01:50:31 CST 2016 223 | */ 224 | public void setEmail(String email) { 225 | this.email = email; 226 | } 227 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/service/CommonService.java: -------------------------------------------------------------------------------- 1 | package com.huan.service; 2 | 3 | import com.huan.model.UserDetail; 4 | import com.huan.model.UserInfo; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * @author 詹欢欢 10 | * @since 2016/7/5 - 22:20 11 | */ 12 | public interface CommonService { 13 | List selectUserInfo(); 14 | 15 | List selectUserDetail(); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/huan/service/Test1Service.java: -------------------------------------------------------------------------------- 1 | package com.huan.service; 2 | 3 | import com.huan.model.UserInfo; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * @author 詹欢欢 9 | * @since 2016/7/5 - 22:18 10 | */ 11 | public interface Test1Service { 12 | 13 | List selectUserInfo(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/huan/service/Test2Service.java: -------------------------------------------------------------------------------- 1 | package com.huan.service; 2 | 3 | import com.huan.model.UserDetail; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * @author 詹欢欢 9 | * @since 2016/7/5 - 22:21 10 | */ 11 | public interface Test2Service { 12 | 13 | List selectUserDetail(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/huan/service/impl/CommonServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.huan.service.impl; 2 | 3 | import com.huan.model.UserDetail; 4 | import com.huan.model.UserInfo; 5 | import com.huan.service.CommonService; 6 | import com.huan.service.Test1Service; 7 | import com.huan.service.Test2Service; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.stereotype.Service; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * @author 詹欢欢 15 | * @since 2016/7/5 - 22:20 16 | */ 17 | @Service 18 | public class CommonServiceImpl implements CommonService { 19 | 20 | @Autowired 21 | private Test1Service test1Service; 22 | @Autowired 23 | private Test2Service test2Service; 24 | 25 | public List selectUserInfo() { 26 | return test1Service.selectUserInfo(); 27 | } 28 | 29 | public List selectUserDetail() { 30 | return test2Service.selectUserDetail(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/huan/service/impl/Test1ServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.huan.service.impl; 2 | 3 | import com.huan.mapper.UserInfoMapper; 4 | import com.huan.model.UserInfo; 5 | import com.huan.service.Test1Service; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.List; 10 | 11 | @Service 12 | public class Test1ServiceImpl implements Test1Service { 13 | 14 | @Autowired 15 | private UserInfoMapper userInfoMapper; 16 | 17 | public List selectUserInfo() { 18 | return userInfoMapper.selectAll(); 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/service/impl/Test2ServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.huan.service.impl; 2 | 3 | import com.huan.mapper.UserDetailMapper; 4 | import com.huan.model.UserDetail; 5 | import com.huan.service.Test2Service; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * @author 詹欢欢 13 | * @since 2016/7/5 - 22:21 14 | */ 15 | @Service 16 | public class Test2ServiceImpl implements Test2Service { 17 | 18 | @Autowired 19 | private UserDetailMapper userDetailMapper; 20 | 21 | public List selectUserDetail() { 22 | return userDetailMapper.selectAll(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/huan/util/Constants.java: -------------------------------------------------------------------------------- 1 | package com.huan.util; 2 | 3 | /** 4 | * @author Jean Seurin 5 | * @version $Id$ 6 | * @since 13/08/15 - 18:36 7 | */ 8 | public class Constants { 9 | 10 | public static final boolean DEBUG = true; 11 | public static final String DATA_ENCODE = "utf-8"; 12 | 13 | public static final String JSON_VIEW_STATUS_SUCCESS = "success"; 14 | public static final String JSON_VIEW_STATUS_FAILED = "failed"; 15 | public static final String JSON_VIEW_STATUS_ERROR = "error"; 16 | public static final String JSON_VIEW_STATUS_UNAUTHORIZED = "unauthorized"; 17 | 18 | public static final String SPRING_PROFILE_PRODUCTION = "prod"; 19 | public static final String SPRING_PROFILE_DEVELOPMENT = "dev"; 20 | public static final String SPRING_PROFILE_TEST = "test"; 21 | public static final String SPRING_PROFILE_FAST = "fast"; 22 | public static final String SPRING_PROFILE_JSE = "jse"; 23 | public static final String SPRING_PROFILE_STAGING = "staging"; 24 | 25 | public static final String LOCAL_SERVER_URL = "http://localhost:8080"; 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/huan/util/DatabaseContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.huan.util; 2 | 3 | /** 4 | * 作用: 5 | * 1、保存一个线程安全的DatabaseType容器 6 | */ 7 | public class DatabaseContextHolder { 8 | private static final ThreadLocal contextHolder = new ThreadLocal<>(); 9 | 10 | public static DatabaseType getDatabaseType(){ 11 | return contextHolder.get(); 12 | } 13 | 14 | public static void setDatabaseType(DatabaseType type) { 15 | contextHolder.set(type); 16 | } 17 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/util/DatabaseType.java: -------------------------------------------------------------------------------- 1 | package com.huan.util; 2 | 3 | /** 4 | * 列出所有的数据源key(常用数据库名称来命名) 5 | * 注意: 6 | * 1)这里数据源与数据库是一对一的 7 | * 2)DatabaseType中的变量名称就是数据库的名称 8 | */ 9 | public enum DatabaseType { 10 | test1, 11 | test2 12 | } -------------------------------------------------------------------------------- /src/main/java/com/huan/util/DynamicDataSource.java: -------------------------------------------------------------------------------- 1 | package com.huan.util; 2 | 3 | import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 4 | 5 | /** 6 | * 动态数据源(需要继承AbstractRoutingDataSource) 7 | */ 8 | public class DynamicDataSource extends AbstractRoutingDataSource { 9 | protected Object determineCurrentLookupKey() { 10 | return DatabaseContextHolder.getDatabaseType(); 11 | } 12 | } -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | 4 | test1-datasource: 5 | driverClassName: com.mysql.jdbc.Driver 6 | url: jdbc:mysql://localhost:3306/database1?characterEncoding=utf8&useSSL=false&serverTimezone=UTC 7 | username: root 8 | password: root 9 | test2-datasource: 10 | driverClassName: com.mysql.jdbc.Driver 11 | url: jdbc:mysql://localhost:3306/database2?characterEncoding=utf8&useSSL=false&serverTimezone=UTC 12 | username: root 13 | password: root 14 | -------------------------------------------------------------------------------- /src/main/resources/database1.sql: -------------------------------------------------------------------------------- 1 | /* 2 | SQLyog Ultimate v11.27 (32 bit) 3 | MySQL - 5.6.27-log : Database - database1 4 | ********************************************************************* 5 | */ 6 | 7 | 8 | /*!40101 SET NAMES utf8 */; 9 | 10 | /*!40101 SET SQL_MODE = '' */; 11 | 12 | /*!40014 SET @OLD_UNIQUE_CHECKS = @@UNIQUE_CHECKS, UNIQUE_CHECKS = 0 */; 13 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS = @@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS = 0 */; 14 | /*!40101 SET @OLD_SQL_MODE = @@SQL_MODE, SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO' */; 15 | /*!40111 SET @OLD_SQL_NOTES = @@SQL_NOTES, SQL_NOTES = 0 */; 16 | CREATE DATABASE /*!32312 IF NOT EXISTS */`database1` /*!40100 DEFAULT CHARACTER SET utf8 */; 17 | 18 | USE `database1`; 19 | 20 | /*Table structure for table `user_info` */ 21 | 22 | DROP TABLE IF EXISTS `user_info`; 23 | 24 | CREATE TABLE `user_info` ( 25 | `id` VARCHAR(100) NOT NULL, 26 | `username` VARCHAR(255) DEFAULT NULL, 27 | `net_name` VARCHAR(255) DEFAULT NULL, 28 | `job` VARCHAR(255) DEFAULT NULL, 29 | `family_native_place` VARCHAR(255) DEFAULT NULL, 30 | `mobile` VARCHAR(100) DEFAULT NULL, 31 | `email` VARCHAR(255) DEFAULT NULL, 32 | PRIMARY KEY (`id`) 33 | ) 34 | ENGINE = InnoDB 35 | DEFAULT CHARSET = utf8; 36 | 37 | /*Data for the table `user_info` */ 38 | 39 | INSERT INTO `user_info` (`id`, `username`, `net_name`, `job`, `family_native_place`, `mobile`, `email`) 40 | VALUES ('1', '詹欢欢', 'heikehuan', 'java后端开发', '湖北省孝感市', '15010699876', '873089996@qq.com'); 41 | 42 | /*!40101 SET SQL_MODE = @OLD_SQL_MODE */; 43 | /*!40014 SET FOREIGN_KEY_CHECKS = @OLD_FOREIGN_KEY_CHECKS */; 44 | /*!40014 SET UNIQUE_CHECKS = @OLD_UNIQUE_CHECKS */; 45 | /*!40111 SET SQL_NOTES = @OLD_SQL_NOTES */; 46 | -------------------------------------------------------------------------------- /src/main/resources/database2.sql: -------------------------------------------------------------------------------- 1 | /* 2 | SQLyog Ultimate v11.27 (32 bit) 3 | MySQL - 5.6.27-log : Database - database2 4 | ********************************************************************* 5 | */ 6 | 7 | /*!40101 SET NAMES utf8 */; 8 | 9 | /*!40101 SET SQL_MODE=''*/; 10 | 11 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 12 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 13 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 14 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 15 | CREATE DATABASE /*!32312 IF NOT EXISTS*/`database2` /*!40100 DEFAULT CHARACTER SET utf8 */; 16 | 17 | USE `database2`; 18 | 19 | /*Table structure for table `user_detail` */ 20 | 21 | DROP TABLE IF EXISTS `user_detail`; 22 | 23 | CREATE TABLE `user_detail` ( 24 | `id` bigint(20) NOT NULL, 25 | `name` varchar(255) DEFAULT NULL, 26 | `qq` varchar(255) DEFAULT NULL, 27 | PRIMARY KEY (`id`) 28 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 29 | 30 | /*Data for the table `user_detail` */ 31 | 32 | insert into `user_detail`(`id`,`name`,`qq`) values (1,'lululu','1231231'); 33 | 34 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 35 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 36 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 37 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 38 | -------------------------------------------------------------------------------- /src/main/resources/generator/generatorConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 30 | 31 | 32 | 33 |
34 |
35 |
36 | -------------------------------------------------------------------------------- /src/main/resources/generator/mybatis_generator_config.properties: -------------------------------------------------------------------------------- 1 | #数据库连接 2 | jdbc.driverClass = com.mysql.jdbc.Driver 3 | jdbc.url =jdbc\:mysql\://localhost\:3306/huan_blog_test?useUnicode\=true&characterEncoding\=utf8 4 | jdbc.user=root 5 | jdbc.password=root 6 | 7 | #c3p0 8 | jdbc.maxPoolSize=50 9 | jdbc.minPoolSize=10 10 | jdbc.maxStatements=100 11 | jdbc.testConnection=true 12 | 13 | # 通用mapper 14 | mapper.plugin = tk.mybatis.mapper.generator.MapperPlugin 15 | mapper.Mapper = tk.mybatis.mapper.common.Mapper 16 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | %d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserDetailMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/mapper/UserInfoMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 24 | delete from user_info 25 | where id = #{id,jdbcType=VARCHAR} 26 | 27 | 28 | 33 | 34 | SELECT LAST_INSERT_ID() 35 | 36 | insert into user_info (username, net_name, job, 37 | family_native_place, mobile, email 38 | ) 39 | values (#{username,jdbcType=VARCHAR}, #{netName,jdbcType=VARCHAR}, #{job,jdbcType=VARCHAR}, 40 | #{familyNativePlace,jdbcType=VARCHAR}, #{mobile,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR} 41 | ) 42 | 43 | 44 | 49 | update user_info 50 | set username = #{username,jdbcType=VARCHAR}, 51 | net_name = #{netName,jdbcType=VARCHAR}, 52 | job = #{job,jdbcType=VARCHAR}, 53 | family_native_place = #{familyNativePlace,jdbcType=VARCHAR}, 54 | mobile = #{mobile,jdbcType=VARCHAR}, 55 | email = #{email,jdbcType=VARCHAR} 56 | where id = #{id,jdbcType=VARCHAR} 57 | 58 | 68 | 77 | --------------------------------------------------------------------------------