连接到多个db(n db)java spring hibernate

时间:2018-04-22 08:23:41

标签: java spring hibernate

我想在春季靴子里制作一个新的MS, 我的应用程序需要连接到多个数据库(现在它的40个不同的服务器,但让我们说N)。 我有一个api,它给我我想要的数据库的用户名和密码。 我想要一张DB地图。 我只看到

上的配置
#application.properties

dbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mydb
jdbc.username = root
jdbc.password = password
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.springhibernate.example.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {


@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.springhibernate.example.model" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
 }

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    return properties;        
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
   HibernateTransactionManager txManager = new HibernateTransactionManager();
   txManager.setSessionFactory(s);
   return txManager;
}

我想做一个api调用来获取cardential然后到init db,是否可能?

2 个答案:

答案 0 :(得分:1)

尝试使用spring transaction manager并为每个db配置任意数量的数据源并定义单独的数据源,然后使用spring和hibernate配置多个数据库。enter link description here

click here to see more

答案 1 :(得分:0)

相关问题