How to configure multiple Hibernate DataSources?

1k views Asked by At

Is it possible to configure multiple data sources within spring session factory?

DataSource 1 is

  java:/comp/env/jdbc/names;

DataSource 2 is

  java:/comp/env/jdbc/address;

Session Factory is working for DataSource 1. How do I include DataSource2?

 <bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">


 <property name="packagesToScan">
   <list>
       <value>myApp.dao</value>
       <value>myApp.domain</value>
   </list>

</property>


<property name="hibernateProperties">
    <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</prop>
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop>
        <prop key="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</prop>
        <prop key="hibernate.connection.datasource">java:/comp/env/jdbc/names</prop>
        <prop key="hibernate.current_session_context_class">thread</prop>

        </props>


        </property>  
    </bean>

Thanks. Your info was very helpful. I went this route.

Solution Hibernate configuring multiple datasources and multiple session factories

2

There are 2 answers

0
M.Faizal On

you can use Spring AbstractRoutingDataSource and provide a implementation of that to switch datasources at run time. take a look at this example

0
prem30488 On

You can do that as following

<bean id="parentDataSource"
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"
     abstract="true">
<property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
<property name="username" value="sa"/>
</bean>

<bean id="goldDataSource" parent="parentDataSource">
  <property name="url" value="jdbc:hsqldb:hsql://localhost:${db.port.gold}/blog"/>
</bean>

<bean id="silverDataSource" parent="parentDataSource">
<property name="url" value="jdbc:hsqldb:hsql://localhost:${db.port.silver}/blog"/>
</bean>

<bean id="bronzeDataSource" parent="parentDataSource">
<property name="url" value="jdbc:hsqldb:hsql://localhost:${db.port.bronze}/blog"/>
</bean>

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:/blog/datasource/db.properties"/>
</bean>