基于SSM框架配置多数据源

项目基于ssm + maven,通过注解可以实现自动切换数据源。

一、pom.xml

  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、结果显示

原文地址:https://www.cnblogs.com/zt19994/p/9012631.html

时间: 2024-10-11 11:02:52

基于SSM框架配置多数据源的相关文章

一个基于SSM框架开发的高并发电商秒杀Web系统

0 前言 一个基于SSM框架的高并发秒杀系统采用IDEA+Maven+SSM+Mysql+Redis+Jetty.Bootstrap/Jquery开发. 通过这个小项目,理清了基于SSM框架开发Web应用的流程以及常见的避坑方法,并在最后简单采用了Redis缓存以及Mysql Procedure对项目进行了高并发优化. 接下来从DAO层.Service层.Web层开发以及高并发优化4个方面梳理整个项目开发过程. 源码地址https://github.com/Allegr0/seckill 项目准

一款基于SSM框架技术的全栈Java web项目(已部署可直接体验)

概述 此项目基于SSM框架技术的Java Web项目,是全栈项目,涉及前端.后端.插件.上线部署等各个板块,项目所有的代码都是自己编码所得,每一步.部分都有清晰的注释,完全不用担心代码混乱,可以轻松.简单.放心全面学习(也不需要版本控制配置).下载后遇到任何问题,我将全力进行解答. 此项目:快编(kuaib)是一款方便快速全能的编辑系统,竭尽全力地将编写.查找.比对.修改.文件下载.上传.查重等所有功能整合于单个页面操作综合操作系统.--另外,此项目已部署:http://yws233.cn:80

基于SSM框架之宜立方商城项目——项目开始准备一(项目需求分析与设计)

网站概要需求 工作内容: 依照我方(我方公司)所述,遵循阿里巴巴网站.京东网站B2C商城内容进行设计开发,以确保实现类似京东网站.淘宝网站购物商城功能为目的,且网站预留B2B接口.项目开发方需提供给我方(我方公司)单体测试.结合测试.综合测试.覆盖率测试报告书,供我方审核 开发环境  操作系统要求:保障用户可以在Linux.Unix.WindowsNT.Windows2000.WindowsXP.Win7.Vista.DOS等操作系统中畅通访问我方(我方公司)主页且无任何技术问题出现.  数据库

基于ssm框架的论坛系统

                                                             基于ssm框架的论坛系统 1.介绍 本论坛系统基于spring,spring mvc,mybatis框架搭建,实现了论坛的基本功能,注册,登录,发帖,浏览等功能. 2.截图 3.源码 源码已上传至我的github,链接为 https://github.com/withstars/Genesis  ,如有需要请自行下载 原文地址:https://www.cnblogs.com/

Java基于ssm框架的restful应用开发

Java基于ssm框架的restful应用开发 好几年都没写过java的应用了,这里记录下使用java ssm框架.jwt如何进行rest应用开发,文中会涉及到全局异常拦截处理.jwt校验.token拦截器等内容. 1.jwt工具类 直接贴代码了,主要包括jwt的sign.verify.decode三个方法,具体实现如下: package com.isoft.util; import java.util.Date; import com.auth0.jwt.JWT; import com.aut

基于ssm框架开发的零食商城源码

很多朋友说要分享一些基于ssm框架开发的项目,在休闲时间搭建和撸一个以ssm框架开发的零食商城源码,详情如下,希望大家能够见解和学习. 首先ssm定义是框架集由Spring.MyBatis两个开源框架整合而成(SpringMVC是Spring中的部分内容),在开发上前后分离,耦合度小,且开发方便快速,效率较高.大家可以把我分享的项目下载下来二次学习或者开发,同时也可用于毕设. 系统分为前后太两大部分,包含管理员.普通用户权限,具有一系列的包含权限,用户信息,商品信息,订单信息,个人中新,购物车下

ssm框架配置过程

1.pom.xml配置 1.1<build>标签中配置<plugins>和<resources>,即插件和资源文件 1.2 <properties>标签中配置自定义的标签,可以在<dependency>中取出 1.3<dependencies>中配置各依赖包,统一管理 2.创建项目用到的包 1.1web层一般用到model,dao,controller,service,utils,security 1.2创建webapp下面的静态资源

基于SSM框架贺州学院校园二手交易平台设计与实现

注:毕业有一段时间了,这里了做一下当年毕设的经验分享. 绪论 随着中国新四大发明的诞生,网购成了千千万万网友们购物的新方式,新的购物方式促进商业的发展,但随着人们生活水平的提高,许多新购置的物品用了没多少天,甚至没多少次就开始嫌弃.就开始不再使用,成为了闲置物品,大量的闲置物品已然爆发式增长. 在网购人群中,学生网购已经是非常常见,随着购物的便捷,学生们四年下来手里头有着太多的闲置的废旧物,一到大四毕业季,学生离校时都会丢弃一些学习资料和生活用具,这些闲置的废旧物造成校园垃圾增长,给环境保洁员工

基于ssm框架设计定做

一,关于我们启思java设计帮做为广大学子提供设计帮做服务!即使您完全不懂程序,或者您忙于实习没时间做.都请交给我们吧.诚信,专业,具有十年java设计及设计代写经验.为您提供全程跟踪服务.确保您顺利通过设计答辩. 联系我们:.扣.扣.号(幺零三贰三七幺贰幺) 二,服务流程我们在确认了设计的要求后,即可开始设计.无定金,2至3个工作日后,由学生验收设计,满意后才付费.不满意,绝不收您一分钱.全国仅此一家!!! 三,服务项目1.java设计:进销存管理系统,网上购物系统,物流管理系统,网上订餐系统