Spring+Hibernate多数据源整合

在一个项目中,可能用到不止一个数据库,这个时候就需要用Hibernate配置多数据源
接上一篇文章:此处在上一篇文章中做一些修改
第一步:修改applicationContext.xml文件、配置多个dataSource.并且配置每个dataSource相对应的sessionFactory,还要配置sessionFactory对应的 transactionManager

修改之后的applicationContext文件如下:

<?xml version="1.0" encoding= "UTF-8"?>
<!-- Application context definition for PetClinic on Hibernate. -->
<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:jee= "http://www.springframework.org/schema/jee" xmlns:tx= "http://www.springframework.org/schema/tx"
       xsi:schemaLocation= "
                  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                  http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
                  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

      <!-- ========================= RESOURCE DEFINITIONS ========================= -->


      <!-- 配置数据源 ,数据源1:100msh_mac数据库 -->
      <bean id ="dataSource1" class= "org.apache.commons.dbcp.BasicDataSource"
             destroy-method= "close" p:driverClassName="com.mysql.jdbc.Driver"
             p:url= "jdbc:mysql://192.168.0.8:3306/100msh_mac" p:username= "root"
             p:password= "100msh@mysql">
             <property name ="initialSize" value="5" />
             <property name ="maxActive" value="100" />
             <property name ="maxIdle" value="30" />
             <property name ="maxWait" value="1000" />
             <property name ="poolPreparedStatements" value= "true" />
             <property name ="defaultAutoCommit" value= "false" />
             <property name ="validationQuery" value= "select 1 from dual" />
             <property name ="testOnBorrow" value="true" />
      </bean >

      <!-- 配置数据源 ,数据源2:100msh_partner数据库 -->
      <bean id ="dataSource2" class= "org.apache.commons.dbcp.BasicDataSource"
             destroy-method= "close" p:driverClassName="com.mysql.jdbc.Driver"
             p:url= "jdbc:mysql://192.168.0.8:3306/100msh_partner" p:username= "root"
             p:password= "100msh@mysql">
             <property name ="initialSize" value="5" />
             <property name ="maxActive" value="100" />
             <property name ="maxIdle" value="30" />
             <property name ="maxWait" value="1000" />
             <property name ="poolPreparedStatements" value= "true" />
             <property name ="defaultAutoCommit" value= "false" />
             <property name ="validationQuery" value= "select 1 from dual" />
             <property name ="testOnBorrow" value="true" />
      </bean >



      <!-- Hibernate SessionFactory Mac,配置来自于100msh_mac的数据库的SessionFactory -->
      <bean id ="sessionFactory"
             class= "org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
             <property name ="dataSource" ref="dataSource1" />
             <property name ="hibernateProperties">
                   <props >
                         <prop key= "hibernate.dialect">${hibernate.dialect} </prop >
                         <prop key= "hibernate.show_sql">${hibernate.show_sql} </prop >
                         <prop key= "hibernate.generate_statistics">${hibernate.generate_statistics} </prop >
                   </props >
             </property >
             <property name ="eventListeners">
                   <map >
                         <entry key ="merge">
                               <bean
                                     class= "org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />
                         </entry >
                   </map >
             </property >
             <property name ="configLocation" value= "classpath:hibernate.cfg.xml" />
             <property name ="useTransactionAwareDataSource" value= "true"></property >
      </bean >


      <!-- Hibernate SessionFactory Partner ,配置来自于100msh_partner的数据库的SessionFactory-->
      <bean id ="sessionFactoryPartner"
             class= "org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
             <property name ="dataSource" ref="dataSource2" />
             <property name ="hibernateProperties">
                   <props >
                         <prop key= "hibernate.dialect">${hibernate.dialect} </prop >
                         <prop key= "hibernate.show_sql">${hibernate.show_sql} </prop >
                         <prop key= "hibernate.generate_statistics">${hibernate.generate_statistics} </prop >
                   </props >
             </property >
             <property name ="eventListeners">
                   <map >
                         <entry key ="merge">
                               <bean
                                     class= "org.springframework.orm.hibernate3.support.IdTransferringMergeEventListener" />
                         </entry >
                   </map >
             </property >
             <property name ="configLocation" value= "classpath:hibernate.cfg.xml" />
             <property name ="useTransactionAwareDataSource" value= "true"></property >
      </bean >


      
      <!-- 配置每个 SessionFactory对应的transactionManager-->
            
      <bean id ="transactionManager"
             class= "org.springframework.orm.hibernate3.HibernateTransactionManager"
             p:sessionFactory-ref= "sessionFactory" />

      <bean id ="transactionManager1"
             class= "org.springframework.orm.hibernate3.HibernateTransactionManager"
             p:sessionFactory-ref= "sessionFactoryPartner" />

      <!-- JDBc事物 <bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource"> <ref local="dataSource" /> </property> </bean> -->

</beans>

第二步:在dao包下新建两个DaoSupport,一个用来连接datasource1的,一个用来连接datasource2的。并且在类中配置他们的sessionFactory和datasource

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class MacDaoSupport extends JdbcDaoSupport {
     protected Logger logger = LoggerFactory.getLogger(this.getClass());
     @Qualifier("sessionFactory")
     SessionFactory sessionFactory;

     protected HibernateDaoSupport hbSupport;

     /**
      * 自动注入数据源并指定为"dataSource" <br>
      * 子类可重写该方法通过 @Qualifier("dataSource") 注解指定其它数据源 </br>
      * */
     @Autowired()
     public void initJdbc( @Qualifier( "dataSource1") DataSource dataSource) {
            super.setDataSource(dataSource);
     }

     /**
      * 自动注入会话工厂并指定为"sessionFactory" <br>
      * 子类可重写该方法通过 @Qualifier("sessionFactory") 注解指定其它会话工厂 </br>
      * */
     @Autowired()
     public void initHbernate(
                 @Qualifier( "sessionFactory") SessionFactory sessionFactory) {
            hbSupport = new HibernateDaoSupport() {
           };
            hbSupport.setSessionFactory(sessionFactory);
     }

     public HibernateTemplate getHbernateTemplate() {
            return hbSupport.getHibernateTemplate();
     }
}


import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class PartnerDaoSupport extends JdbcDaoSupport {
     protected Logger logger = LoggerFactory.getLogger(this.getClass());
     @Qualifier("sessionFactoryPartner")
     SessionFactory sessionFactory;

     protected HibernateDaoSupport hbSupport;

     /**
      * 自动注入数据源并指定为"dataSource" <br>
      * 子类可重写该方法通过 @Qualifier("dataSource") 注解指定其它数据源 </br>
      * */
     @Autowired()
     public void initJdbc( @Qualifier( "dataSource2") DataSource dataSource) {
            super.setDataSource(dataSource);
           setDataSource(dataSource);
     }

     /**
      * 自动注入会话工厂并指定为"sessionFactory" <br>
      * 子类可重写该方法通过 @Qualifier("sessionFactory") 注解指定其它会话工厂 </br>
      * */
     @Autowired()
     public void initHbernate(
                 @Qualifier( "sessionFactoryPartner") SessionFactory sessionFactory) {
            hbSupport = new HibernateDaoSupport() {
           };
            hbSupport.setSessionFactory(sessionFactory);
     }

     public HibernateTemplate getHbernateTemplate() {
            return hbSupport.getHibernateTemplate();
     }
     
     
}



第三步:使用方法
对于不同的XXXXServiceImpl类,如果AServiceImpl里面的方法全部都是访问dataSource1的数据库。 那就将该类继承 MacDaoSupport(该类配置了datasource的来源是datasource1,就是ApplicationContext中的datasource1)
相同,如果是BserviceImpl里面的方法全部是访问dataSource2的数据库,就继承  PartnerDaoSupport  
那么问题来了,如果 AServiceImpl既要访问 dataSource1的数据库,又要访问 dataSource2的数据库.怎么办?
昨天下午弄了半天. 利用动态切换数据库来实行,但是一个下午没弄出来。请教了几个java的同事,
他们的做法是: AServiceImpl里面的方法全部必须访问的数据源是同一个! 也就是说:有几个数据源,就有几个XXXDaoSupport


这是访问数据库100msh_mac的(datasource1)
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bmsh.router.assistant.dao.MacDaoSupport;
import com.bmsh.router.assistant.entity.Machine;
import com.bmsh.router.assistant.service.MacService;
import com.bmsh.router.assistant.util.ObjectMapper2;

@Service
@Transactional
public class MacServiceImpl extends MacDaoSupport implements MacService {
     Logger log = Logger.getLogger(MacServiceImpl.class);

     @Override
     public List<Machine> queryMachine() {
            // TODO Auto-generated method stub
           String sql = "select * from t_machine_type";
           
            return getJdbcTemplate().query(sql, new ObjectMapper2(Machine.class ));
     }

}

这是访问100msh_partner的数据库(dataSource2)

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bmsh.router.assistant.dao.PartnerDaoSupport;
import com.bmsh.router.assistant.entity.Tag;
import com.bmsh.router.assistant.service.PartnerService;
import com.bmsh.router.assistant.util.ObjectMapper2;
@Service
@Transactional
public class PartnerServiceImpl extends PartnerDaoSupport implements
           PartnerService {
     Logger log = Logger.getLogger(PartnerServiceImpl.class);

     @Override
     public List<Tag> queryTag() {
           String sql = "select * from anl_tag";
            return getJdbcTemplate().query(sql, new ObjectMapper2(Tag.class ));
     }

}


DEMO下载:http://download.csdn.net/detail/q908555281/9345959

你可能感兴趣的:(spring,Hibernate,hibernate多数据源)