项目中有多个数据库,就得配置多数据源并支持动态切换,列举重点部分
1、数据库配置文件db.properties,这里使用了c3p0连接池
c3p0.pool.size.max=10
c3p0.pool.size.min=5
c3p0.pool.size.ini=3
c3p0.pool.size.increment=5
bbs.driverClassName=com.mysql.jdbc.Driver
bbs.url=jdbc:mysql://localhost:3306/bbsnew
bbs.username=root
bbs.password=123456
shop.driverClassName=com.mysql.jdbc.Driver
shop.url=jdbc:mysql://localhost:3306/shopnew
shop.username=root
shop.password=123456
2、修改spring 的核心配置文件applicationContext.xml,重点multipleDataSource
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.isea533.mybatis.mapper" />
<property name="properties">
<value>
mappers=tk.mybatis.mapper.common.Mapper
</value>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:config/db.properties</value>
</list>
</property>
</bean>
<!-- 1. 数据源1 : bbsDataSource -->
<bean id="bbsDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${bbs.driverClassName}" />
<property name="jdbcUrl" value="${bbs.url}" />
<property name="user" value="${bbs.username}" />
<property name="password" value="${bbs.password}" />
<property name="maxPoolSize" value="${c3p0.pool.size.max}" />
<property name="minPoolSize" value="${c3p0.pool.size.min}" />
<property name="initialPoolSize" value="${c3p0.pool.size.ini}" />
<property name="acquireIncrement" value="${c3p0.pool.size.increment}" />
</bean>
<!-- 1. 数据源 2: shopDataSource -->
<bean id="shopDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${shop.driverClassName}" />
<property name="jdbcUrl" value="${shop.url}" />
<property name="user" value="${shop.username}" />
<property name="password" value="${shop.password}" />
<property name="maxPoolSize" value="${c3p0.pool.size.max}" />
<property name="minPoolSize" value="${c3p0.pool.size.min}" />
<property name="initialPoolSize" value="${c3p0.pool.size.ini}" />
<property name="acquireIncrement" value="${c3p0.pool.size.increment}" />
</bean>
<!-- 配置多数据源 -->
<bean id="multipleDataSource" class="com.ihefe.util.MultipleDataSource">
<property name="defaultTargetDataSource" ref="bbsDataSource" />
<property name="targetDataSources">
<map>
<entry key="bbsDataSource" value-ref="bbsDataSource" />
<entry key="shopDataSource" value-ref="shopDataSource" />
</map>
</property>
</bean>
<!-- 2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource:引用数据源 MyBatis定义数据源,同意加载配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="multipleDataSource"></property>
<property name="configLocation" value="classpath:config/mybatis-config.xml" />
</bean>
<!-- 3. mybatis自动扫描加载Sql映射文件/接口 : MapperScannerConfigurer sqlSessionFactory basePackage:指定sql映射文件/接口所在的包(自动扫描) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ihefe.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- 4. 事务管理 : DataSourceTransactionManager dataSource:引用上面定义的数据源 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref bean="multipleDataSource" />
</property>
</bean>
<!-- 5. 使用声明式事务 transaction-manager:引用上面定义的事务管理器 -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- 注解扫描包 -->
<context:component-scan base-package="com.ihefe" />
</beans>
并使用ThreadLocal解决线程安全问题
MultipleDataSource.java
package com.ihefe.util;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class MultipleDataSource extends AbstractRoutingDataSource {
private static final ThreadLocal<String> dataSourceKey = new InheritableThreadLocal<String>();
public static void setDataSourceKey(String dataSource) {
dataSourceKey.set(dataSource);
}
@Override
protected Object determineCurrentLookupKey() {
return dataSourceKey.get();
}
}
4、调用示例(contoller层)
UserController.java部分
/**
* 获取所有用户列表
*
* @param request
* @return
*/
@RequestMapping("list")
public String list(HttpServletRequest request) {
MultipleDataSource.setDataSourceKey("shopDataSource");
List<User> list = userService.findAll();
request.setAttribute("list", list);
MultipleDataSource.setDataSourceKey("shopDataSource");
Map<String, String> map = new HashMap<String, String>();
map.put("sql", "select max(id) from ih_user");
int id=userService.getMaxId(map);
System.out.println(id);
// return getSqlSession().selectOne(getMybatisMapperNamesapce()+ ".getMaxId", map);
return "user/list";
}