Spring+hibernate 配置多数据源

项目中我们经常会遇到多数据源的问题,尤其是数据同步或定时任务等项目更是如此。多数据源让人最头痛的,不是配置多个数据源,而是如何能灵活动态的切换数据源。例如在一个spring和hibernate的框架的项目中,我们在spring配置中往往是配置一个dataSource来连接数据库,然后绑定给sessionFactory,在dao层代码中再指定sessionFactory来进行数据库操作。

正如上图所示,每一块都是指定绑死的,如果是多个数据源,也只能是下图中那种方式。

可看出在Dao层代码中写死了两个SessionFactory,这样日后如果再多一个数据源,还要改代码添加一个SessionFactory,显然这并不符合开闭原则。

那么正确的做法应该是

1. applicationContext.xml如下

<span style="font-size:12px;"><?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
       	   http://www.springframework.org/schema/beans/spring-beans-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/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">
           
    <context:annotation-config />
    <!-- 隐式地向 Spring 容器注册
    AutowiredAnnotationBeanPostProcessor、
    CommonAnnotationBeanPostProcessor、
    PersistenceAnnotationBeanPostProcessor、
    RequiredAnnotationBeanPostProcessor  -->
	<context:component-scan base-package="com.saleSystem,com.interfaces" /><!-- 扫描包中的所有Bean,配置扫描包路径选项 -->
	<tx:annotation-driven transaction-manager="txManager" /><!--@Transactional这个注解进行的驱动,这是基于注解的方式使用事务配置声明 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>classpath:app/jdbc.properties</value>
		</property>
	</bean>

	<bean id="parentDataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />		
        <property name="initialSize" value="5" />
        <property name="maxActive" value="50" />
        <property name="maxIdle" value="50" />
        <property name="minIdle" value="0" />
        <property name="maxWait" value="6000" />
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <property name="minEvictableIdleTimeMillis" value="25200000" />
	</bean>
	
	<bean id="adminDataSource" parent="parentDataSource">  
        <property name="url" value="${jdbc.url}" />
    </bean>  
       
    <bean id="logDataSource" parent="parentDataSource">  
        <property name="url" value="${log.url}" />
    </bean>  	
	<bean id="dataSource" class="com.datasource.DynamicDataSource">  
       <property name="targetDataSources">  
          <map key-type="java.lang.String">  
             <entry key="logDataSource" value-ref="logDataSource"/>  
          </map>  
       </property>  
       <property name="defaultTargetDataSource" ref="adminDataSource"/>  
    </bean>  
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />

		<!-- hibernate 方言 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="javax.persistence.validation.mode">none</prop>
				<prop key="hibernate.format_sql">false</prop>
				<prop key="hibernate.hbm2ddl.auto">validate</prop>
			</props>
		</property>

		<property name="mappingDirectoryLocations">
			<list>
				<value>
					classpath:hibernate
				</value>
			</list>
		</property>
	</bean>
	
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 面向切面控制权限 -->
	 <aop:config>
		<aop:pointcut expression="execution(public * com.saleSystem.services..*.* (..))"
			id="bussinessService" />
		<aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice" />
	</aop:config>

	<!-- 谏言 -->
	<!-- 事务 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true" /><!--以get开头的方法只能从数据库中读取数据  -->
			<tx:method name="find*" read-only="true" />
			<tx:method name="query*" read-only="true"/>
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />
            
			<tx:method name="add*" propagation="REQUIRED" rollback-for="Exception"/><!--以add开头的方法能对数据库进行查询、新增、删除、编辑1  -->
            <tx:method name="edit*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="save*" propagation="REQUIRED" rollback-for="Exception" />
			<tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="remove*" propagation="REQUIRED" rollback-for="Exception"/>
			<tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="modify*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="repair" propagation="REQUIRED" rollback-for="Exception"/>
           <tx:method name="deleteAndRepair" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="put*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="restart*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="stop*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="change*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="check*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="start*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="porkDiv" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="send*" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="porkRej" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="porkPdtRej" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="loginTimeAdd" propagation="REQUIRED" rollback-for="Exception"/>   
            <tx:method name="productSaleBySaleIdAndType" propagation="REQUIRED" rollback-for="Exception"/>
            <tx:method name="sale*" propagation="REQUIRED"/>      
		</tx:attributes>
	</tx:advice>
</beans></span>


2. DynamicDataSource.java

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

public class DynamicDataSource extends AbstractRoutingDataSource {

	protected Object determineCurrentLookupKey() {
		return CustomerContextHolder.getCustomerType();
	}

}

3.CustomerContextHolder.java

public class CustomerContextHolder {
	private static final ThreadLocal contextHolder = new ThreadLocal();

	public static void setCustomerType(String customerType) {
		contextHolder.set(customerType);
	}

	public static String getCustomerType() {
		return (String) contextHolder.get();
	}

	public static void clearCustomerType() {
		contextHolder.remove();
	}

}



在《 Hibernate 与 Spring 多数据源的配置》中提到

 CustomerContextHolder.setCustomerType(DataSourceMap.Admin);//设置数据源

但是实际运用中,无需再选择数据源,Spring会自动根据不同的Model找到相应的数据源。

另外AbstractRoutingDataSource类也可以实现主从表读写分离,目前还未尝试,但是通过AOP+Annotation即可。



参考:1. 《spring多数据源配置

    2. 《Hibernate 与 Spring 多数据源的配置




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值