在我们的项目开发过程中,经常需要在同一个项目中运用多个数据库中的数据资源,所以我们经常会在同一个项目连接多个数据库进行开发,今天我们来实现一下在Spring+Mybatis框架下实现多数据源的配置:
1、项目准备:
a、项目中所使用的jar包,该项目通过maven进行jar包的引用
<span style="font-size:18px;"><properties> <org.springframework.version>4.0.0.RELEASE</org.springframework.version> <javax.servlet.version>2.5</javax.servlet.version> <com.alibaba.druid.version>0.2.15</com.alibaba.druid.version> <org.mybatis.mybatis.spring.version>1.2.2</org.mybatis.mybatis.spring.version> <mysql.connector.java.version>5.1.21</mysql.connector.java.version> <org.mybatis.version>3.1.1</org.mybatis.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${javax.servlet.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${com.alibaba.druid.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${org.mybatis.mybatis.spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.java.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${org.mybatis.version}</version> </dependency> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>ibatis-sqlmap</artifactId> <version>2.3.4.726</version> </dependency> </dependencies></span>
在该项目中,我们虽然配置了DispatcherServlet的上下文springmvc-servlet.xml,但是只是创建了这样的一个空文件,没有进行任何的实用的配置,这是因为我们已经配置了Spring的上下文,而Spring的上下文其实和DispatcherServlet是可以共用同一个上下文的,如果我们分别创建上下文的话容易造成一些不必要的麻烦
<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>datacenter</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 加载Spring容器配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <!-- encode filter --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 页面请求 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <!-- ajax请求 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.json</url-pattern> </servlet-mapping> </web-app></span>
2、项目结构
我们将两个数据中的各自的东西分别放在两个名字相同的文件夹下,然后通过one和two来进行区分,项目中共用的东西则不进行区分,这里对项目结构中的每一个包的功能进行一个简单的介绍:
a、domainOne和domainTwo分别用来存放两个不同的数据中的想对应的数据库表的实体类
b、mapperOne和mapperTwo分别用来存放与mybatis所使用的sql语句对应的xml文件的同名接口,用来进行Service中的调用
c、serviceOne和serviceTwo分别存放两个数据库表中对应的数据操作的方法和过程,连接controller和mapper
d、Resource中的mapper_one和mapper_two分别用来存放mybatis在查询过程中所使用的sql语句对应的.xml文件
e、spring中的applicationContext.xml文件中主要进行Spring的上下文的配置和初始化信息配置
f、sping中的applicationContext-dataSource.xml主要是对数据库连接信息和mybatis进行相关配置
g、init-config.properties主要用来存放数据库连接变量和连接配置信息
h、mybatis-config-one.xml和mybatis-config-two.xml主要用来配置实体类的别名信息
接下来,我们看一下每一个类和配置信息的具体实现吧
3、项目实现
a、我们按照项目的初始化过程来看一下这些代码,项目启动中首先会进行初始化的是applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> <import resource="classpath:spring/applicationContext-web.xml"/> <import resource="classpath:spring/applicationContext-dataSource.xml"/> <context:component-scan base-package="com.quncao.datacenter"/> <!-- annotation默认的方法映射适配器 --> <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> </beans>
b、接下来上面的applicationContext.xml会分别的去调用applicationContext-web.xml文件和applicationContext-dataSource.xml文件,这里的applicationContext-web.xml主要是对于前端页面相关信息进行了简单的配置:我们这里简单看一下applicationContext-web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--前端视图解析--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="order" value="1"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
c、接下来我们这个项目的重头戏来了,多数据源的配置主要在applicationContext-dataSource.xml文件中进行配置的,我们现在看一下这个文件的配置过程:
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:spring/init-config.properties</value> </property> </bean> <!--数据源1--> <bean id="dataSourceOne" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!--配置基本属性--> <property name="url" value="${dataSourceOne.url}"/> <property name="username" value="${dataSourceOne.username}"/> <property name="password" value="${dataSourceOne.password}"/> <property name="connectionProperties" value="${dataSourceOne.driver}"/> <!--配置初始化大小--> <property name="initialSize" value="1"/> <property name="minIdle" value="1"/> <property name="maxActive" value="20"/> <!--配置获取连接等待超时时间--> <property name="maxWait" value="60000"/> <!--配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒--> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!--配置一个连接在池中最小的生存的时间,单位是毫秒--> <property name="minEvictableIdleTimeMillis" value="30000"/> <property name="validationQuery" value="SELECT 'x'"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <!--打开PSCache,并且制定每个连接上PSCache的大小--> <property name="poolPreparedStatements" value="false"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <!--配置监控统计拦截的filters--> <property name="filters" value="stat"/> </bean> <!--define the SqlSessionFactory--> <bean id="sqlSessionFactoryOne" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSourceOne"/> <property name="configLocation" value="classpath:spring/mybatis-config-one.xml"/> <property name="mapperLocations" value="classpath:mapper_one/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryOne"/> <property name="basePackage" value="com.quncao.datacenter.mybatis.mapperOne"/> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSourceOne"/> <qualifier value="dataOne"/> </bean> <!--全注解方式,需加上@Transactional--> <tx:annotation-driven transaction-manager="transactionManager"/> <!--事务控制的业务方法配置--> <!-- <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="page*" read-only="true"/> <tx:method name="list*" read-only="true"/> <tx:method name="*"/> </tx:attributes> </tx:advice> --> <!--事务控制拦截--> <!--<aop:config proxy-target-class="true"> <aop:advisor pointcut="execution(* com.quncao.datacenter..*.service.*Service.*(..))" advice-ref="txAdvice"/> </aop:config> --> <!-- <context:component-scan base-package="com.quncao.datacenter.mybatis"/> <context:annotation-config /> --> <!--数据源2--> <bean id="dataSourceTwo" class="com.alibaba.druid.pool.DruidDataSource"> <property name="url" value="${dataSourceTwo.url}"/> <property name="username" value="${dataSourceTwo.username}"/> <property name="password" value="${dataSourceTwo.password}"/> <property name="connectionProperties" value="${dataSourceTwo.driver}"/> <property name="initialSize" value="${initialSize}"/> <property name="minIdle" value="${minIdle}"/> <property name="maxActive" value="${maxActive}"/> <property name="maxWait" value="${maxWait}"/> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}"/> <property name="validationQuery" value="SELECT 'x'"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <property name="poolPreparedStatements" value="false"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <property name="filters" value="stat"/> </bean> <bean id="sqlSessionFactoryTwo" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSourceTwo"/> <property name="configLocation" value="classpath:spring/mybatis-config-two.xml"/> <property name="mapperLocations" value="classpath:mapper_two/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryTwo"/> <property name="basePackage" value="com.quncao.datacenter.mybatis.mapperTwo"/> </bean> <bean id="transactionManagerTwo" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSourceTwo"/> <qualifier value="dataTwo"/> </bean> <tx:annotation-driven transaction-manager="transactionManagerTwo"/> </beans>
d、剩下的就是数据库连接信息和初始化配置信息的配置 init-config.properties
<!--数据库连接池配置--> <!--datacenter数据库--> dataSourceOne.driver=com.mysql.jdbc.Driver dataSourceOne.url=jdbc:mysql://127.0.0.1:3306/dataOne dataSourceOne.username=root dataSourceOne.password=root <!--datasystem--> dataSourceTwo.driver=com.mysql.jdbc.Driver dataSourceTwo.url=jdbc:mysql://127.0.0.1:3306/dataTwo dataSourceTwo.username=root dataSourceTwo.password=root <!--公共配置--> initialSize=1 minIdle=1 maxActive=20 maxWait=60000 timeBetweenEvictionRunsMillis=60000 minEvictableIdleTimeMillis=300000
e、最后就是mybatis-config-one.xml和mybatis-config-two.xml文件的配置啦
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="false"/> <setting name="defaultExecutorType" value="REUSE"/> <setting name="useGeneratedKeys" value="true"/> </settings> <typeAliases> <typeAlias type="com.quncao.datacenter.mybatis.domainOne.TbSystem" alias="TbSystem" /> </typeAliases> <typeHandlers> </typeHandlers> <mappers> </mappers> </configuration>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.quncao.datacenter.mybatis.mapperOne.SystemMapper"> <resultMap type="TbSystem" id="TbSystem"> <result property="id" column="id"/> <result property="name" column="name"/> <result property="url" column="url"/> </resultMap> <select id="getById" parameterType="Integer" resultType="TbSystem"> SELECT * from tb_system where id = #{id} </select> </mapper>
g、与SystemMapper.xml想对应的便是和他们名字相同的SystemMapper.java的接口啦
package com.quncao.datacenter.mybatis.mapperOne; import com.quncao.datacenter.mybatis.domainOne.TbSystem; /** * Created by zhang on 16/3/15. */ public interface SystemMapper { TbSystem getById(Integer id); }
h、调用这个接口的便是我们的service文件,service文件会通过继承BaseService来确定调用哪一个数据中的信息,所以每一个Service文件都需要继承该数据库想对应的父类
我们首先来看一下BaseServiceOne.java中的内容,该类为一个抽象类,只要目的是为了通过注解的方式确定数据源和数据的回滚
package com.quncao.datacenter.mybatis.serviceOne; import org.springframework.transaction.annotation.Transactional; /** * Created by zhang on 16/3/15. */ @Transactional(value="dataOne",rollbackFor = Exception.class) public abstract class BaseServiceOne { }
接下来是具体的SystemService.java的实现
package com.quncao.datacenter.mybatis.serviceOne; import com.quncao.datacenter.mybatis.domainOne.TbSystem; import com.quncao.datacenter.mybatis.mapperOne.SystemMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by zhang on 16/3/15. */ @Service("systemService") public class SystemService extends BaseServiceOne { @Autowired private SystemMapper systemMapper; public TbSystem getById(int id){ return systemMapper.getById(id); } }
最后就是Controller的实现啦
package com.quncao.datacenter.controller; import com.quncao.datacenter.mybatis.domainOne.TbSystem; import com.quncao.datacenter.mybatis.domainTwo.TbUser; import com.quncao.datacenter.mybatis.mapperTwo.UserMapper; import com.quncao.datacenter.mybatis.serviceOne.SystemService; import com.quncao.datacenter.mybatis.serviceTwo.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; /** * Created by zhang on 16/3/14. */ @Controller() @RequestMapping("system") public class SystemController { @Autowired private SystemService systemService; @Autowired private UserService userService; /** * 登录预加载 * @return */ @RequestMapping("preLogin") public ModelAndView preLogin(){ ModelAndView mav = new ModelAndView(); ModelMap mm = mav.getModelMap(); mm.put("message",""); mav.setViewName("login"); return mav; } @RequestMapping("login") public ModelAndView login(HttpServletRequest request){ ModelAndView mav = new ModelAndView(); ModelMap mm = mav.getModelMap(); String username = request.getParameter("username"); String password = request.getParameter("password"); if(username!=null && !"".equals(username)){ TbUser user = userService.getUserByName(username); if (user != null) { if(password.equals(user.getPassword())){ try { mm.put("message","欢迎您的登录"); mm.put("user",user); TbSystem system = systemService.getById(1); mm.put("system",system); } catch (Exception e ) { e.printStackTrace(); } mav.setViewName("main"); }else{ mm.put("message","您输入的用户名或者密码错误"); mav.setViewName("login"); } }else{ mm.put("message","该用户不存在"); mav.setViewName("login"); } } return mav; } }
这样,一个基于Spring和Mybatis框架进行的多数据源的框架就这样实现了,在这个创建的过程中一定会有各种各样的困难,其实在我们克服这些困难的过程正是我们掌握技能的过程,祝大家成功