Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring boot dynamically change database

How do i change database in running Spring Boot application? I need to connect another db when RestController got request with connection parameters. Here is part of my RestController.

@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);
}

To clear things. I m new to Spring and Spring Boot. So i would like to see a solution without old fashion Spring xmls. Here is my current database configuration.

@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;
    }
}
like image 399
Kirill Sukhanov Avatar asked May 25 '16 10:05

Kirill Sukhanov


1 Answers

You can use AbstractRoutingDataSource that selects a specific datasource at runtime based on some criteria.

Please take a look at this sample :

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

like image 158
shankarsh15 Avatar answered Oct 30 '22 13:10

shankarsh15