Good evening, what is the correct and common approach of handling two or more databases?
Consider this HibernateConfiguration class configuring only one datasource:
@Configuration @EnableTransactionManagement
@PropertySource(value = { "classpath:hibernate.properties" })
public class HibernateConfiguration {
@Autowired
private Environment env;
@Bean
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// ... setting data source
return dataSource;
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
// ... setting Hibernate properties
return properties;
}
@Bean
public LocalSessionFactoryBean getSessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(getDataSource());
sessionFactory.setPackagesToScan(new String[] { "POJOs'" });
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
@Bean public HibernateTransactionManager transactionManager(SessionFactory sf) {
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sf);
return htm;
}
}
Is recommended to let one class configure one datasource? Or is enough to configure all at once? How do I specify in Dao class which SessionFactory will be used and what is the recommended approach in case of switching two exact same databases on two different hosting servers?
The example DAOs. First I need to switch between Foo and Bar.
@Repository
public class RepositoryImpl implements RepositoryDao {
@Autowired // Here I need to switch between databases "foo" and "bar"
private SessionFactory sessionFactory;
...
The second one I need fixed on example database Foo.
@Repository
public class FooImpl implements FooDao {
@Autowired // Here I need fixed on "Foo"
private SessionFactory sessionFactory;
@Qualifierto sessionFactory injection to distinguish between 2 factories. So I suggest 2 config classes for each datasource with 2 sessions and 2 transaction managers.