晚上好, 处理两个或多个数据库的正确和常用方法是什么?
考虑这个HibernateConfiguration类只配置一个数据源:
{"a"=>{"b"=>{}, "c"=>{}}, "d"=>{"e"=>{}}}
{"a"=>{"b"=>{"x"=>"y"}, "z"=>1}}
{"a"=>{"b"=>{"x"=>"y"}, "c"=>{}}, "d"=>{"e"=>{}}}
{"a"=>{"b"=>{"x"=>"y"}, "c"=>{}}, "d"=>{"e"=>{}}}
建议让一个类配置一个数据源?或者足以一次配置所有?如何在Dao类中指定将使用哪个SessionFactory以及在两个不同的托管服务器上切换两个完全相同的数据库时推荐的方法是什么?
示例DAO。首先,我需要在@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;
}
}
和Foo
之间切换。
Bar
我需要在示例数据库@Repository
public class RepositoryImpl implements RepositoryDao {
@Autowired // Here I need to switch between databases "foo" and "bar"
private SessionFactory sessionFactory;
...
上修复第二个。
Foo
答案 0 :(得分:1)
一种方法
@Bean
@Primary
@ConfigurationProperties("app.datasource.foo")
public DataSourceProperties fooDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.foo")
public DataSource fooDataSource() {
return fooDataSourceProperties().initializeDataSourceBuilder().build();
}
@Bean
@ConfigurationProperties("app.datasource.bar")
public BasicDataSource barDataSource() {
return (BasicDataSource) DataSourceBuilder.create()
.type(BasicDataSource.class).build();
}
Spring multiple datasources config
其他方法可能是:从orm.xml
加载不同的映射(persistence.xml
)或在实体类中引用不同的模式。