Search code examples
hibernatehibernate-mappingmultiple-databases

Multiple DataBases using Hibernate in Annotation Style


There have been multiple discussions on this topic in the site but I am using annotations all across to create sessionFactory.

private SessionFactory sessionFactory;

@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;

This is how hibernate.cfg.xml looks like

<hibernate-configuration>
<session-factory>
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.password">xxxxx</property>
    <property name="hibernate.connection.url">xxxxx</property>
    <property name="hibernate.connection.username">XXXX</property>
    <property name="hibernate.connection.characterEncoding">utf-8</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
    <property name="hibernate.format_sql">true</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.use_sql_comments">true</property>
    <mapping class="XXXX" />
</session-factory>
</hibernate-configuration>

This is applicationContext.xml

<!-- add tomcat datasource instance to springs context -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/XXXXDS" />
    <property name="resourceRef" value="true" />
</bean>

How do I achieve multiple DB integration in this case. One solution that I came across was to create multiple hibernate.cfg.xml and create another session factory for it.

But I have two doubts, 1) How do I indicate in autowiring, which sessionFactory to pick, 2) I will have to duplicate lot of info across hibernate.xml, for example beans. Is there any cleaner approach for this issue?


Solution

  • First question: @Autowired with @Qualifier("name") will help you to pick which sessionFatory.

    @Autowired
    @Qualifier("sessionFactoryName")
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    ...
    }
    

    Second question: you can set hibernate properties: schema and catalog to specify database when working on multiple databases. I have the experience with MS SQL Server, so in entity I added annotation @Table("[database].[schema].[tablename]") and it mapping to the specific table in multiple databases.