How can I define multiple sessionfactory instances in Spring?

13,057

Solution 1

You might define an abstract bean and use bean inheritance. This means you'll have a bean definition that works as a template and you may have multiple beans just copying the attributes set by the parent bean.

Here's an example:

<bean id="abstractSessionFactory" abstract="true"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="mappingResources">
      <list>
        <value>product.hbm.xml</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.HSQLDialect
      </value>
    </property>
</bean>

<bean id="mySessionFactory" parent="abstractSessionFactory">
    <property name="dataSource" ref="myDataSource"/>
    ...
</bean>

<bean id="mySessionFactory2" parent="abstractSessionFactory">
    <property name="dataSource" ref="myDataSource2"/>
    ...
</bean>

Using the attribute 'abstract' you ensure that bean won't be instantiated and it will be used just as a template.

More info here: link text

Solution 2

Are you sure you need multiple SessionFactories? If all the mappings/configurations are the same and you just have multiple identical databases (e.g. in a multi-tenant app?), then how about having a single SessionFactory that connects to a DataSource which dynamically supplies the appropriate database connection?

See this question for more details:

And this blog post on Dynamic DataSource Routing in Spring.

Share:
13,057

Related videos on Youtube

Chris R
Author by

Chris R

I'm a software developer and inveterate geek (like many here, I suspect). For work I use so many tools I usually can't remember them all, but recently they've been heavily Python/Java. C, Java/J2EE, various scripting and release engineering tools figure heavily in the list as well.

Updated on April 17, 2022

Comments

  • Chris R
    Chris R about 2 years

    I would like to have multiple Hibernate SessionFactories in a spring application, all of them with identical configurations except for the DataSource. Ideally, I would acquire a particular SessionFactory by name. I need to be able to do this based on runtime state, and it isn't possible to determine which session factories I will need at application startup time. Basically, I need a SessionFactoryTemplate or something like it.

    Is this possible? How do I go about doing it?

  • Chris R
    Chris R about 15 years
    I've clarified my description to explain why it's not the right answer. Thanks, though!
  • Pintac
    Pintac over 11 years
    Hi. The mappings are the same but it points to different schema/Database.
  • Pintac
    Pintac over 11 years
    Hi was thinking of this but how would you instantiate the different sessionfactories.