基于SSM框架配置多数据源
项目基于ssm + maven,通过注解可以实现自动切换数据源。
一、pom.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.multipleDataSource</groupId> 8 <artifactId>multipleDataSource</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 <packaging>war</packaging> 11 12 <name>multipleDataSource Maven Webapp</name> 13 <!-- FIXME change it to the project's website --> 14 <url>http://www.example.com</url> 15 16 <properties> 17 <org.springframework.version>4.2.4.RELEASE</org.springframework.version> 18 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 19 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 20 <maven.compiler.encoding>UTF-8</maven.compiler.encoding> 21 <maven.compiler.source>1.7</maven.compiler.source> 22 <maven.compiler.target>1.7</maven.compiler.target> 23 <jackson.version>2.8.5</jackson.version> 24 25 <org.mybatis.version>3.4.1</org.mybatis.version> 26 <org.mybatis.spring.version>1.3.0</org.mybatis.spring.version> 27 </properties> 28 29 <dependencies> 30 <dependency> 31 <groupId>org.apache.tomcat</groupId> 32 <artifactId>tomcat-servlet-api</artifactId> 33 <version>7.0.64</version> 34 </dependency> 35 36 <dependency> 37 <groupId>org.springframework</groupId> 38 <artifactId>spring-core</artifactId> 39 <version>${org.springframework.version}</version> 40 </dependency> 41 42 <dependency> 43 <groupId>org.springframework</groupId> 44 <artifactId>spring-expression</artifactId> 45 <version>${org.springframework.version}</version> 46 </dependency> 47 48 <dependency> 49 <groupId>org.springframework</groupId> 50 <artifactId>spring-beans</artifactId> 51 <version>${org.springframework.version}</version> 52 </dependency> 53 54 <dependency> 55 <groupId>org.springframework</groupId> 56 <artifactId>spring-aop</artifactId> 57 <version>${org.springframework.version}</version> 58 </dependency> 59 60 <dependency> 61 <groupId>org.springframework</groupId> 62 <artifactId>spring-context</artifactId> 63 <version>${org.springframework.version}</version> 64 </dependency> 65 66 <dependency> 67 <groupId>org.springframework</groupId> 68 <artifactId>spring-webmvc</artifactId> 69 <version>${org.springframework.version}</version> 70 </dependency> 71 72 <dependency> 73 <groupId>org.springframework</groupId> 74 <artifactId>spring-oxm</artifactId> 75 <version>${org.springframework.version}</version> 76 </dependency> 77 78 <dependency> 79 <groupId>org.springframework</groupId> 80 <artifactId>spring-jdbc</artifactId> 81 <version>${org.springframework.version}</version> 82 </dependency> 83 84 <dependency> 85 <groupId>org.springframework</groupId> 86 <artifactId>spring-tx</artifactId> 87 <version>${org.springframework.version}</version> 88 </dependency> 89 90 <dependency> 91 <groupId>org.springframework</groupId> 92 <artifactId>spring-web</artifactId> 93 <version>${org.springframework.version}</version> 94 </dependency> 95 96 <dependency> 97 <groupId>org.springframework</groupId> 98 <artifactId>spring-test</artifactId> 99 <version>${org.springframework.version}</version> 100 </dependency> 101 102 <dependency> 103 <groupId>org.aspectj</groupId> 104 <artifactId>aspectjweaver</artifactId> 105 <version>1.7.3</version> 106 </dependency> 107 108 <dependency> 109 <groupId>org.mybatis</groupId> 110 <artifactId>mybatis-spring</artifactId> 111 <version>${org.mybatis.spring.version}</version> 112 </dependency> 113 <dependency> 114 <groupId>org.mybatis</groupId> 115 <artifactId>mybatis</artifactId> 116 <version>${org.mybatis.version}</version> 117 </dependency> 118 119 <dependency> 120 <groupId>org.aspectj</groupId> 121 <artifactId>aspectjrt</artifactId> 122 <version>1.6.11</version> 123 </dependency> 124 125 <dependency> 126 <groupId>org.codehaus.jackson</groupId> 127 <artifactId>jackson-mapper-asl</artifactId> 128 <version>1.9.12</version> 129 </dependency> 130 131 <dependency> 132 <groupId>commons-dbcp</groupId> 133 <artifactId>commons-dbcp</artifactId> 134 <version>1.4</version> 135 <!--<scope>runtime</scope>--> 136 </dependency> 137 138 <dependency> 139 <groupId>ch.qos.logback</groupId> 140 <artifactId>logback-classic</artifactId> 141 <version>1.1.2</version> 142 <scope>compile</scope> 143 </dependency> 144 <dependency> 145 <groupId>ch.qos.logback</groupId> 146 <artifactId>logback-core</artifactId> 147 <version>1.1.2</version> 148 <scope>compile</scope> 149 </dependency> 150 151 <dependency> 152 <groupId>mysql</groupId> 153 <artifactId>mysql-connector-java</artifactId> 154 <version>5.1.6</version> 155 </dependency> 156 157 <dependency> 158 <groupId>com.google.guava</groupId> 159 <artifactId>guava</artifactId> 160 <version>20.0</version> 161 </dependency> 162 163 164 <dependency> 165 <groupId>org.apache.commons</groupId> 166 <artifactId>commons-lang3</artifactId> 167 <version>3.5</version> 168 </dependency> 169 170 171 <dependency> 172 <groupId>commons-collections</groupId> 173 <artifactId>commons-collections</artifactId> 174 <version>3.2.1</version> 175 </dependency> 176 177 <dependency> 178 <groupId>com</groupId> 179 <artifactId>druid</artifactId> 180 <version>1.0.9</version> 181 </dependency> 182 183 <dependency> 184 <groupId>javax.servlet</groupId> 185 <artifactId>jstl</artifactId> 186 <version>1.2</version> 187 </dependency> 188 189 <dependency> 190 <groupId>taglibs</groupId> 191 <artifactId>standard</artifactId> 192 <version>1.1.2</version> 193 </dependency> 194 195 <!-- jackson --> 196 <dependency> 197 <groupId>com.fasterxml.jackson.core</groupId> 198 <artifactId>jackson-core</artifactId> 199 <version>${jackson.version}</version> 200 </dependency> 201 <dependency> 202 <groupId>com.fasterxml.jackson.core</groupId> 203 <artifactId>jackson-databind</artifactId> 204 <version>${jackson.version}</version> 205 </dependency> 206 <dependency> 207 <groupId>com.fasterxml.jackson.core</groupId> 208 <artifactId>jackson-annotations</artifactId> 209 <version>${jackson.version}</version> 210 </dependency> 211 212 213 <dependency> 214 <groupId>junit</groupId> 215 <artifactId>junit</artifactId> 216 <version>4.11</version> 217 <scope>test</scope> 218 </dependency> 219 </dependencies> 220 221 <build> 222 <finalName>multipleDataSource</finalName> 223 <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> 224 <plugins> 225 <plugin> 226 <artifactId>maven-clean-plugin</artifactId> 227 <version>3.0.0</version> 228 </plugin> 229 <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> 230 <plugin> 231 <artifactId>maven-resources-plugin</artifactId> 232 <version>3.0.2</version> 233 </plugin> 234 <plugin> 235 <artifactId>maven-compiler-plugin</artifactId> 236 <version>3.7.0</version> 237 </plugin> 238 <plugin> 239 <artifactId>maven-surefire-plugin</artifactId> 240 <version>2.20.1</version> 241 </plugin> 242 <plugin> 243 <artifactId>maven-war-plugin</artifactId> 244 <version>3.2.0</version> 245 </plugin> 246 <plugin> 247 <artifactId>maven-install-plugin</artifactId> 248 <version>2.5.2</version> 249 </plugin> 250 <plugin> 251 <artifactId>maven-deploy-plugin</artifactId> 252 <version>2.8.2</version> 253 </plugin> 254 </plugins> 255 </pluginManagement> 256 </build> 257 </project>
二、web.xml
1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 5 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xmlns="http://java.sun.com/xml/ns/javaee" 7 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 8 id="WebApp_ID" version="2.5"> 9 <display-name>Archetype Created Web Application</display-name> 10 11 12 <!--过滤器,转码用的 /* 拦截所有路径--> 13 <filter> 14 <filter-name>characterEncodingFilter</filter-name> 15 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 16 <init-param> 17 <param-name>encoding</param-name> 18 <param-value>UTF-8</param-value> 19 </init-param> 20 <init-param> 21 <param-name>forceEncoding</param-name> 22 <param-value>true</param-value> 23 </init-param> 24 </filter> 25 <filter-mapping> 26 <filter-name>characterEncodingFilter</filter-name> 27 <url-pattern>/*</url-pattern> 28 </filter-mapping> 29 30 31 <!--前端分发器--> 32 <servlet> 33 <servlet-name>dispatcherServlet</servlet-name> 34 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 35 <!--扫描springMVC配置文件--> 36 <init-param> 37 <param-name>contextConfigLocation</param-name> 38 <param-value> 39 classpath:ApplicationContext.xml 40 </param-value> 41 </init-param> 42 <!--设置优先级最高级--> 43 <load-on-startup>1</load-on-startup> 44 </servlet> 45 <servlet-mapping> 46 <servlet-name>dispatcherServlet</servlet-name> 47 <url-pattern>/</url-pattern> 48 </servlet-mapping> 49 </web-app>
三、ApplicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-4.0.xsd 11 http://www.springframework.org/schema/tx 12 http://www.springframework.org/schema/tx/spring-tx-4.0.xsd 13 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 14 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 15 16 <!--注解配置--> 17 <context:annotation-config/> 18 19 <mvc:annotation-driven > 20 <mvc:message-converters> 21 <bean class="org.springframework.http.converter.StringHttpMessageConverter"/> 22 <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/> 23 </mvc:message-converters> 24 </mvc:annotation-driven> 25 26 <!--扫描controller和service层--> 27 <context:component-scan base-package="com.multipleDataSource.controller,com.multipleDataSource.service" annotation-config="true"/> 28 29 <!--<context:annotation-config/>--> 30 <aop:aspectj-autoproxy/> 31 32 <!-- jdbc.properties文件路径 --> 33 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 34 <property name="locations"> 35 <list> 36 <value>classpath:jdbc.properties</value> 37 38 </list> 39 </property> <!--value="classpath:/com/ningpai/web/config/jdbc.properties" />--> 40 </bean> 41 42 <!-- 数据源的配置 --> 43 <bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource" 44 init-method="init" destroy-method="close"> 45 <property name="driverClassName" value="${jdbc.driver}"/> 46 <property name="url" value="${jdbc.url}"/> 47 <property name="username" value="${jdbc.username}"/> 48 <property name="password" value="${jdbc.password}"/> 49 </bean> 50 51 <!--第二个数据源--> 52 <bean name="dataSource2" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 53 <property name="driverClassName" value="${jdbc.driver_2}"/> 54 <property name="url" value="${jdbc.url_2}"/> 55 <property name="username" value="${jdbc.username_2}"/> 56 <property name="password" value="${jdbc.password_2}"/> 57 </bean> 58 59 <!-- 下面的是切换数据库的自定义类 --> 60 <bean id="multipleDataSource" class="com.multipleDataSource.common.DynamicDataSource"> 61 <property name="targetDataSources"> 62 <map key-type="java.lang.String"> 63 <entry key="dataSource1" value-ref="dataSource1"></entry> 64 <entry key="dateSource2" value-ref="dataSource2"></entry> 65 </map> 66 </property> 67 <property name="defaultTargetDataSource" ref="dataSource1"></property> 68 </bean> 69 70 <!--事务相关控制--> 71 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 72 <property name="dataSource" ref="multipleDataSource"/> 73 </bean> 74 <!-- 使用@Transactional进行声明式事务管理需要声明下面这行 --> 75 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" order="2"/> 76 77 <!-- MyBatis sqlSessionFactory 配置 mybatis--> 78 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 79 <property name="dataSource" ref="multipleDataSource"/> 80 <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"/> 81 </bean> 82 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 83 <constructor-arg index="0" ref="sqlSessionFactory"/> 84 </bean> 85 86 87 <!-- JdbcTemplate使用动态数据源的配置 --> 88 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 89 <property name="dataSource"> 90 <ref bean="multipleDataSource"/> 91 </property> 92 </bean> 93 94 <bean name="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 95 <property name="basePackage" value="com.multipleDataSource.dao"/> 96 </bean> 97 98 <!--前缀和后缀配置--> 99 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 100 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> 101 <property name="prefix" value="/WEB-INF/views/"/> 102 <property name="suffix" value=".jsp"/> 103 </bean> 104 105 <!-- 激活自动代理功能 --> 106 <aop:aspectj-autoproxy proxy-target-class="true"/> 107 108 <bean id="dataSourceAspect" class="com.multipleDataSource.common.aspect.DataSourceAspect"/> 109 110 <aop:config> 111 <aop:aspect id="c" ref="dataSourceAspect"> 112 <aop:pointcut id="tx" expression="execution(* com.multipleDataSource.dao..*.*(..))"/> 113 <aop:before pointcut-ref="tx" method="before"/> 114 </aop:aspect> 115 </aop:config> 116 </beans>
四、jdbc.properties
1 jdbc.url=jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8&relaxAutoCommit=true&zeroDateTimeBehavior=convertToNull 2 jdbc.username=root 3 jdbc.password=123456 4 jdbc.driver=com.mysql.jdbc.Driver 5 6 jdbc.driver_2=com.mysql.jdbc.Driver 7 jdbc.url_2=jdbc:mysql://localhost:3306/city?useUnicode=true&characterEncoding=UTF-8&relaxAutoCommit=true&zeroDateTimeBehavior=convertToNull 8 jdbc.username_2=root 9 jdbc.password_2=123456
五、自定义DynamicDataSource 类
实现自动切换数据源,通过自定义DataSource注解,切面管理。
1、数据源上下文 DataSourceContextHolder
1 package com.multipleDataSource.common; 2 3 /** 4 * 数据源上下文类 5 * @author zhongtao on 2018/5/5 6 */ 7 public class DataSourceContextHolder { 8 private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); 9 10 public static void setDbType(String dbType) { 11 contextHolder.set(dbType); 12 } 13 14 public static String getDbType() { 15 return ((String) contextHolder.get()); 16 } 17 18 public static void clearDbType() { 19 contextHolder.remove(); 20 } 21 }
2、DynamicDataSource 类
1 package com.multipleDataSource.common; 2 3 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 4 5 /** 6 * 动态转换数据源 7 * @author zhongtao on 2018/5/5 8 */ 9 public class DynamicDataSource extends AbstractRoutingDataSource { 10 @Override 11 protected Object determineCurrentLookupKey() { 12 return DataSourceContextHolder.getDbType(); 13 } 14 }
3、DataSource 注解类
1 package com.multipleDataSource.annotation; 2 3 import java.lang.annotation.ElementType; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6 import java.lang.annotation.Target; 7 8 /** 9 * 注解类 10 * @author zhongtao on 2018/5/7 11 */ 12 @Retention(RetentionPolicy.RUNTIME) 13 @Target(ElementType.METHOD) 14 public @interface DataSource { 15 String value(); 16 }
4、DataSourceAspect 切面管理
1 package com.multipleDataSource.common.aspect; 2 3 import com.multipleDataSource.annotation.DataSource; 4 import com.multipleDataSource.common.DataSourceContextHolder; 5 import org.aspectj.lang.JoinPoint; 6 import org.aspectj.lang.annotation.Before; 7 import org.aspectj.lang.reflect.MethodSignature; 8 9 import java.lang.reflect.Method; 10 11 /** 12 * 数据源切面类 13 * 14 * @author zhongtao on 2018/5/7 15 */ 16 public class DataSourceAspect { 17 public void pointCut() { 18 } 19 20 @Before(value = "pointCut()") 21 public void before(JoinPoint point) { 22 //拦截的实体类 23 Object target = point.getTarget(); 24 //拦截的方法名 25 String methodName = point.getSignature().getName(); 26 //接口 27 Class<?>[] interfaces = target.getClass().getInterfaces(); 28 //拦截的放置参数类型 29 Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes(); 30 31 try { 32 Method method = interfaces[0].getMethod(methodName, parameterTypes); 33 if (method != null && method.isAnnotationPresent(DataSource.class)) { 34 DataSource data = method.getAnnotation(DataSource.class); 35 DataSourceContextHolder.setDbType(data.value()); 36 } 37 } catch (Exception e) { 38 e.printStackTrace(); 39 } 40 } 41 }
5、数据源类型
1 package com.multipleDataSource.common; 2 3 /** 4 * 数据源类型 需要和ApplicationContext.xml中的multipleDataSource下的key相同 5 * @author zhongtao on 2018/5/5 6 */ 7 public class DataSourceType { 8 public static final String MYSQL1 = "dataSource1"; 9 10 public static final String MYSQL2 = "dateSource2"; 11 }
六、pojo类
1、User类
1 package com.multipleDataSource.pojo; 2 3 /** 4 * @author zhongtao on 2018/5/7 5 */ 6 public class User { 7 8 private Integer id; 9 10 /** 11 * 用户名 12 */ 13 private String userName; 14 15 /** 16 * 描述 17 */ 18 private String description; 19 20 private City city; 21 22 public Integer getId() { 23 return id; 24 } 25 26 public void setId(Integer id) { 27 this.id = id; 28 } 29 30 public String getUserName() { 31 return userName; 32 } 33 34 public void setUserName(String userName) { 35 this.userName = userName; 36 } 37 38 public String getDescription() { 39 return description; 40 } 41 42 public void setDescription(String description) { 43 this.description = description; 44 } 45 46 public City getCity() { 47 return city; 48 } 49 50 public void setCity(City city) { 51 this.city = city; 52 } 53 }
2、City类
1 package com.multipleDataSource.pojo; 2 3 /** 4 * @author zhongtao on 2018/5/7 5 */ 6 public class City { 7 /** 8 * 城市编号 9 */ 10 private Long id; 11 12 /** 13 * 省份编号 14 */ 15 private Long provinceId; 16 17 /** 18 * 城市名称 19 */ 20 private String cityName; 21 22 /** 23 * 描述 24 */ 25 private String description; 26 27 public Long getId() { 28 return id; 29 } 30 31 public void setId(Long id) { 32 this.id = id; 33 } 34 35 public Long getProvinceId() { 36 return provinceId; 37 } 38 39 public void setProvinceId(Long provinceId) { 40 this.provinceId = provinceId; 41 } 42 43 public String getCityName() { 44 return cityName; 45 } 46 47 public void setCityName(String cityName) { 48 this.cityName = cityName; 49 } 50 51 public String getDescription() { 52 return description; 53 } 54 55 public void setDescription(String description) { 56 this.description = description; 57 } 58 }
3、ResultVo类
1 package com.multipleDataSource.pojo; 2 3 /** 4 * @author zhongtao on 2018/5/7 5 */ 6 public class ResultVo<T> { 7 8 private boolean success = true; 9 private String code ="0000"; 10 private String msg; 11 private T data; 12 13 public boolean isSuccess() { 14 return success; 15 } 16 17 public void setSuccess(boolean success) { 18 this.success = success; 19 } 20 21 public String getCode() { 22 return code; 23 } 24 25 public void setCode(String code) { 26 this.code = code; 27 } 28 29 public String getMsg() { 30 return msg; 31 } 32 33 public void setMsg(String msg) { 34 this.msg = msg; 35 } 36 37 public T getData() { 38 return data; 39 } 40 41 public void setData(T data) { 42 this.data = data; 43 } 44 }
七、controller层
1、UserController类
1 package com.multipleDataSource.controller; 2 3 import com.multipleDataSource.pojo.ResultVo; 4 import com.multipleDataSource.pojo.User; 5 import com.multipleDataSource.service.UserService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Controller; 8 import org.springframework.util.StringUtils; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.RequestParam; 11 import org.springframework.web.bind.annotation.ResponseBody; 12 import org.springframework.web.servlet.ModelAndView; 13 14 /** 15 * @author zhongtao on 2018/5/7 16 */ 17 @Controller 18 public class UserController { 19 20 @Autowired 21 private UserService userService; 22 23 /** 24 * 获取数据 25 * @param userName 26 * @return 27 */ 28 @RequestMapping(value = "/getData") 29 @ResponseBody 30 public ResultVo getName(@RequestParam(value = "userName") String userName) { 31 ResultVo<Object> resultVo = new ResultVo<>(); 32 if (userName==null){ 33 resultVo.setMsg("用户名错误"); 34 resultVo.setCode("0001"); 35 }else { 36 User user = userService.findByName(userName); 37 if(!StringUtils.isEmpty(user)){ 38 resultVo.setMsg("测试成功"); 39 resultVo.setData(user); 40 } 41 } 42 return resultVo; 43 } 44 }
八、service层
1、UserService层
1 package com.multipleDataSource.service; 2 3 import com.multipleDataSource.pojo.User; 4 5 /** 6 * 用户类接口 7 * @author zhongtao on 2018/5/7 8 */ 9 public interface UserService { 10 11 /** 12 * 根据用户名获取用户信息,包括从库的地址信息 13 * 14 * @param userName 15 * @return 16 */ 17 User findByName(String userName); 18 }
2、UserServiceImpl
1 package com.multipleDataSource.service.impl; 2 3 import com.multipleDataSource.dao.CityDao; 4 import com.multipleDataSource.dao.UserDao; 5 import com.multipleDataSource.pojo.City; 6 import com.multipleDataSource.pojo.User; 7 import com.multipleDataSource.service.UserService; 8 import org.springframework.beans.factory.annotation.Autowired; 9 import org.springframework.stereotype.Service; 10 11 /** 12 * @author zhongtao on 2018/5/7 13 */ 14 @Service 15 public class UserServiceImpl implements UserService{ 16 @Autowired 17 private UserDao userDao; // 数据源1 18 19 @Autowired 20 private CityDao cityDao; // 数据源2 21 22 @Override 23 public User findByName(String userName) { 24 User user = userDao.findByName(userName); 25 City city = cityDao.findByName("成都市"); 26 user.setCity(city); 27 return user; 28 } 29 }
九、dao层
1、UserDao类
1 package com.multipleDataSource.dao; 2 3 import com.multipleDataSource.pojo.User; 4 import org.apache.ibatis.annotations.Mapper; 5 import org.apache.ibatis.annotations.Param; 6 7 /** 8 * @author zhongtao on 2018/5/7 9 */ 10 @Mapper 11 public interface UserDao { 12 13 /** 14 * 根据用户名获取用户信息 默认数据源不用加 DataSource标签 15 * 16 * @param userName 17 * @return 18 */ 19 User findByName(@Param("userName") String userName); 20 }
2、CityDao类
1 package com.multipleDataSource.dao; 2 3 import com.multipleDataSource.annotation.DataSource; 4 import com.multipleDataSource.common.DataSourceType; 5 import com.multipleDataSource.pojo.City; 6 import org.apache.ibatis.annotations.Mapper; 7 import org.apache.ibatis.annotations.Param; 8 9 /** 10 * @author zhongtao on 2018/5/7 11 */ 12 @Mapper 13 public interface CityDao { 14 /** 15 * 根据城市名称,查询城市信息 需要加上 DataSource标签,自动切换数据源 16 * 17 * @param cityName 城市名 18 */ 19 @DataSource(DataSourceType.MYSQL2) 20 City findByName(@Param("cityName") String cityName); 21 }
十、mapper文件
1、UserMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 4 <mapper namespace="com.multipleDataSource.dao.UserDao"> 5 <resultMap id="BaseResultMap" type="com.multipleDataSource.pojo.User"> 6 <result column="id" property="id" /> 7 <result column="user_name" property="userName" /> 8 <result column="description" property="description" /> 9 </resultMap> 10 11 <parameterMap id="User" type="com.multipleDataSource.pojo.User"/> 12 13 <sql id="Base_Column_List"> 14 id, user_name, description 15 </sql> 16 17 <select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String"> 18 select 19 <include refid="Base_Column_List" /> 20 from user 21 where user_name = #{userName} 22 </select> 23 </mapper>
2、CityMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.multipleDataSource.dao.CityDao"> 4 <resultMap id="BaseResultMap" type="com.multipleDataSource.pojo.City"> 5 <result column="id" property="id" /> 6 <result column="province_id" property="provinceId" /> 7 <result column="city_name" property="cityName" /> 8 <result column="description" property="description" /> 9 </resultMap> 10 11 <parameterMap id="City" type="com.multipleDataSource.pojo.City"/> 12 13 <sql id="Base_Column_List"> 14 id, province_id, city_name, description 15 </sql> 16 17 <select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String"> 18 select 19 <include refid="Base_Column_List" /> 20 from city 21 where city_name = #{cityName} 22 </select> 23 24 </mapper>
十一、测试
1、网址输入
2、结果显示