首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >spring boot动态变更数据库

spring boot动态变更数据库
EN

Stack Overflow用户
提问于 2016-05-25 18:33:12
回答 1查看 14.9K关注 0票数 8

如何在运行Spring Boot应用程序时更改数据库?当RestController收到带有连接参数的请求时,我需要连接另一个数据库。这是我的RestController的一部分。

代码语言:javascript
复制
@RequestMapping(value = "/change",method = RequestMethod.GET)
public ResponseEntity<?> change(@RequestParam String ip, @RequestParam String port,
                                @RequestParam String dbname, @RequestParam String username,
                                @RequestParam String password ){
    //change datasource here
    return new ResponseEntity<>(HttpStatus.OK);
}

把事情弄清楚。我是Spring和Spring Boot的新手。因此,我希望看到一个没有老式的Spring xmls的解决方案。这是我当前的数据库配置。

代码语言:javascript
复制
@Configuration
@EnableJpaRepositories("su.asgor.dao")
@EnableTransactionManagement
@ComponentScan("su.asgor")
public class DatabaseConfig {

    @Bean
    public DataSource dataSource() {
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl("jdbc:postgresql://localhost:5432/portal74");
        ds.setDriverClassName("org.postgresql.Driver");
        ds.setUsername("postgres");
        ds.setPassword("system");

        ds.setInitialSize(30);
        ds.setMinIdle(30);
        ds.setMaxIdle(60);
        ds.setTimeBetweenEvictionRunsMillis(30000);
        ds.setMinEvictableIdleTimeMillis(60000);
        ds.setTestOnBorrow(true);
        ds.setValidationQuery("select version()");
        return ds;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan("su.asgor.model");
        em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());

        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect","org.hibernate.dialect.PostgreSQL9Dialect");
        hibernateProperties.put("hibernate.show_sql","false");
        hibernateProperties.put("hibernate.hbm2ddl.auto","update");

        em.setJpaProperties(hibernateProperties);
        return em;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager manager = new JpaTransactionManager();
        manager.setEntityManagerFactory(entityManagerFactory().getObject());
        return manager;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-25 20:02:12

您可以使用在运行时根据某些条件选择特定datasourceAbstractRoutingDataSource

请看下面的示例:

https://spring.io/blog/2007/01/23/dynamic-datasource-routing/

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37434518

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档