springMVC+mybatis+多數據源項目搭建

1、基本介紹

多數據源只不過在dao層配置多配置一個數據庫驅動連接信息,添加一個切換數據庫對象,設置一個主要默認數據庫,須要其餘數據庫須要操做室利用公共數據庫切換類實現數據庫切換。java

###2、配置mysql

1.基本web.xml配置不變和普通配置springmvc同樣web

2.spring上下文配置也不變springMVC-context.xmlspring

3.jdbc.properties雙數據庫源sql

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://127.0.0.1\:3306/datebasename?useUnicode\=true&characterEncoding\=utf-8
username=root
password=root


driver2=oracle.jdbc.driver.OracleDriver
url2=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:XE  
username2=ROOT
password2=ROOT

4.spring-dao.xml數據庫鏈接 注意每個數據庫配置id,後面數據庫切換工具類要使用數據庫

<?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">
	<!-- 引入jdbc配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<!-- 數據源配置1 -->
	<bean id="mysqlData" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${driver}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<property name="initialSize" value="5" />        <!-- 初始鏈接數量 -->
		<property name="maxActive" value="30" />         <!-- 最大鏈接數量 -->
		<property name="maxIdle" value="5" />            <!-- 空閒鏈接數量 -->
		<property name="maxWait" value="60000" />       <!-- 一個查詢1分鐘內沒有返回,自動放棄 -->
		<property name="validationQuery" value="SELECT 1" />   <!-- 數據庫鏈接可用性測試語句 -->
		<property name="testOnBorrow" value="true" />          <!-- 每次獲取一個鏈接的時候,驗證一下鏈接是否可用,語句在validationQuery裏面 -->
		<property name="removeAbandoned" value="true" />       <!-- 自動處理鏈接未關閉的問題,Setting this to true can recover db connections from poorly written applications which fail to close a connection. -->
		<property name="removeAbandonedTimeout" value="300" /> <!-- 鏈接使用後5分鐘未關閉,則拋棄 -->
	</bean>


	<!-- 數據源配置 2 -->
	<bean id="oracleData" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${driver2}" />
		<property name="url" value="${url2}" />
		<property name="username" value="${username2}" />
		<property name="password" value="${password2}" />
		<property name="initialSize" value="5" />        <!-- 初始鏈接數量 -->
		<property name="maxActive" value="30" />         <!-- 最大鏈接數量 -->
		<property name="maxIdle" value="5" />            <!-- 空閒鏈接數量 -->
		<property name="maxWait" value="60000" />       <!-- 一個查詢1分鐘內沒有返回,自動放棄 -->

		<property name="validationQuery" value="select 1 from dual" />   <!-- oracle數據庫鏈接可用性測試語句 -->
		<property name="testOnBorrow" value="true" />          <!-- 每次獲取一個鏈接的時候,驗證一下鏈接是否可用,語句在validationQuery裏面 -->
		<property name="removeAbandoned" value="true" />       <!-- 自動處理鏈接未關閉的問題,Setting this to true can recover db connections from poorly written applications which fail to close a connection. -->
		<property name="removeAbandonedTimeout" value="300" /> <!-- 鏈接使用後5分鐘未關閉,則拋棄 -->
	</bean>

	<!-- 動態配置數據源   -->
	<bean id="dataSource" class="com.xxxx.dataSource.DynamicDataSource">
		<property name="targetDataSources">
			<map key-type="java.lang.String">
				<entry value-ref="mysqlData" key="mysqlData"></entry>
				<entry value-ref="oracleData" key="oracleData"></entry>
			</map>
		</property>
		<property name="defaultTargetDataSource" ref="mysqlData"></property>      <!-- 默認使用mysql的數據源 -->
	</bean>



	<!-- MyBatis配置  建立SqlSessionFactory-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="typeAliasesPackage" value="com.xxxx.entity" />
	</bean>
	<!--dao層接口和mybatis映射xml在同一目錄下 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.xxxx.dao" />
	</bean>
</beans>

5.spring-service.xml 事務配置(已經註釋掉)express

<?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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
     <context:component-scan base-package="com.wanliyun.service" />
	<!-- 事務控制  對MyBatis操做數據庫  spring使用JDBC事務控制類 -->
 	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
	  <property name="dataSource" ref="dataSource"/> 
 	</bean>
	<!-- 實現基於註解的事務管理 -->
<!--     <tx:annotation-driven transaction-manager="txManager" /> -->
    
	<!--  配置事務傳播特性 -->
<!--  	<tx:advice id="TestAdvice" transaction-manager="transactionManager">                                              -->
<!--  	    <tx:attributes>  -->
<!--   			<tx:method name="save*"  propagation="REQUIRED"/>   -->
<!--   			<tx:method name="del*"  propagation="REQUIRED"/>  -->
<!--   			<tx:method name="update*"  propagation="REQUIRED"/>   -->
<!--   			<tx:method name="add*"  propagation="REQUIRED"/>  -->
<!--   			<tx:method name="modify*"  propagation="REQUIRED"/>   -->
<!--   			<tx:method name="find*"  propagation="REQUIRED"/>   -->
<!-- 			<tx:method name="get*"  propagation="REQUIRED"/>   -->
<!--  			<tx:method name="apply*" propagation="REQUIRED"/> -->
<!--  			<tx:method name="*" propagation="REQUIRED"/>   -->
<!--   	    </tx:attributes>   -->
<!--   	</tx:advice>   -->
	<!--  配置參與事務的類 <aop:advisor  pointcut="execution(* com.zhcv.vote.*.service.*.*(..)) advice-ref="TestAdvice"/> -->
<!--   <aop:config> -->
<!-- 		<aop:pointcut id="allTestServiceMethod" expression="execution(* com.wanliyun.service.*.*(..))"/> -->
<!-- 		<aop:advisor pointcut-ref="allTestServiceMethod" advice-ref="TestAdvice" /> -->
<!-- 	</aop:config> -->
  
</beans>

6.三個java工具類apache

/**
 * 
 */
package com.wanliyun.dataSource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 寫一個DynamicDataSource類來繼承AbstractRoutingDataSource,
 * 並重寫determineCurrentLookupKey()方法,來達到動態切換數據庫
 * 
 * @author lennon
 * @time 2017-4-26 下午3:17:59
 * @version
 */
public class DynamicDataSource extends AbstractRoutingDataSource {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#
	 * determineCurrentLookupKey()
	 */
	@Override
	protected Object determineCurrentLookupKey() {
		// TODO Auto-generated method stub
		return DatabaseContextHolder.getDbType();
	}

}

注意下面這工具中的數據庫要與dao配置中的數據源id相同mybatis

/**
 * 
 */
package com.wanliyun.dataSource;

/**
 * [@author](https://my.oschina.net/arthor) lennon 數據源配置
 * [@time](https://my.oschina.net/u/126678) 2017-4-26 下午5:11:13
 * [@version](https://my.oschina.net/u/931210)
 */
public class DataSourceType {
	public static String MysqlType = "mysqlData";
	public static String OracleType = "oracleData";
	static {

	}
}
/**
 * 
 */
package com.wanliyun.dataSource;

/**
 * [@author](https://my.oschina.net/arthor) lennon 切換數據源類
 * 
 * [@time](https://my.oschina.net/u/126678) 2017-4-26 下午3:16:17
 * @version
 */

public class DatabaseContextHolder {
	private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

	// 設置要使用的數據源
	public static void setDbType(String dbType) {
		contextHolder.set(dbType);
	}

	// 獲取數據源
	public static String getDbType() {
		return contextHolder.get();
	}

	// 清除數據源,使用默認的數據源
	public static void clearDbType() {
		contextHolder.remove();
	}

	/**
	 * @author lennon
	 * 
	 * @param args
	 * @time 2017-4-26 下午3:16:17
	 * @version
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

7.其餘spring項目的配置註解使用 都不變 該怎麼用還怎麼用 只要注意切換數據庫mvc

/**
 * controller
 */
package com.wanliyun.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wanliyun.dataSource.DataSourceType;
import com.wanliyun.dataSource.DatabaseContextHolder;
import com.wanliyun.service.UserService;

/**
 * @author lennon
 * 
 * @time 2017-4-26 下午5:19:36
 * @version
 */
@Controller
public class UserController {
	@Resource
	UserService UserService;

	@RequestMapping(value = "user")
	public void saveUser(HttpServletRequest request, HttpServletResponse response) {
              //切換數據源
		DatabaseContextHolder.setDbType(DataSourceType.OracleType);
		UserService.save();
	}
}
/**
 * service
 */
package com.wanliyun.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wanliyun.dao.UserMapper;
import com.wanliyun.entity.User;
import com.wanliyun.mongoDao.mongoDao;

/**
 * @author lennon
 * 
 * @time 2017-4-26 下午5:19:58
 * @version
 */
@Service
public class UserService {
	@Autowired
	UserMapper UserMapper;

	public void save() {

		User user = new User();
		user.setUserName("chen");
		mongoDao mongoDao = new mongoDao();
		mongoDao.insert(user);
	}
}

就是這樣沒什麼特別之處,記錄一下方便之後方便查看

相關文章
相關標籤/搜索