Kushal
Kushal

Reputation: 81

How can I develop an application which will run on more than one database at a same time using Spring + Hibernate?

I am developing a Java application using Spring + Hibernate. i want this application to run on more then one Database on same time.

For Example if user tries to search for some data, Application has to search for that data in all the configured data-sources at a same time.

I am looking for a solution which will create different threads for each data-source and when user perform any operation all the threads needs to perform that operation

Edit 1 Let me explain my problem in detail below is my DAO class

@Repository("engineDAO")
public class EngineDAOImpl implements EngineDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void persistEngine(Engine engine, String[] DataSourceNames) {
        sessionFactory.getCurrentSession().persist(engine);
    }
}

Now from service class i will call persistEngine method of EngineDAO class with argument as String[] DataSourceNames so this operation needs to be performed on all the Data-sources provided as argument. What all changes i have to make for this? Thanks in advance

Upvotes: 0

Views: 165

Answers (1)

Maroš Tyrpák
Maroš Tyrpák

Reputation: 305

You can have multiple SessionFactory or EntityManagerFactory objects, each associated with different DataSource. If you want to manage transaction across different datasources I would recommend to use JTA Transaction Manager. If your application is not running in Java EE environment, you can use some 3rd party JTA transaction manager, for example Atomikos Transaction Manager

There are some threads at Stackoverflow that discuss about this problem. Try this

Edit 1: If you neet to select datasources by name, than your DAO can implement BeanFactoryAware and you will obtain BeanFactory object, which you can use for accessing SessionFactory beans by name. Your code should look like something like that

@Repository("engineDAO")
public class EngineDAOImpl implements EngineDAO, BeanFactoryAware {

    private org.springframework.beans.factory.BeanFactory beanFactory;

    @Override
    public void persistEngine(final Engine engine, final String[] sessionFactoryNames) {
        for (final String sessionFactoryName : sessionFactoryNames) {
            final SessionFactory sessionFactory = beanFactory.getBean(sessionFactoryName, SessionFactory.class);
            sessionFactory.getCurrentSession().persist(engine);
        }
    }

    @Override
    public void setBeanFactory(final BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}

Upvotes: 1

Related Questions