简体   繁体   中英

Multiple Database connections at runtime using spring -jdbc or hibernate

I have one master db. After login with master db I have some another db. Is it possible to connect at runtime to second db and also have instanace of first db also(master db) application using spring-jdbc or hibernate, thanks in advance.

Yes, sure. You can create as many data sources as you need. Just define them in the Spring Context and autowire in you classes. This question might help you with defining components with the same type but different names.

UPD1: you can create a datasource at runtime just like that:

    DataSource ds = new DataSource();
    ds.setUsername("username");
    ds.setPassword("password");
    ds.setDriverClassName("com.mysql.jdbc.Driver"); // or another driver
    ds.setUrl("jdbc:mysql://{hostname}:{port}/{dbName}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false");
    ds.setTestWhileIdle(true);
    ds.setTestOnBorrow(true);
    ds.setTestOnReturn(false);
    ds.setValidationQuery("/* ping */ SELECT 1");
    ds.setValidationQueryTimeout(1);
    ds.setValidationInterval(30000);
    ds.setTimeBetweenEvictionRunsMillis(30000);        
    ds.setMinIdle(1);
    ds.setMaxWait(10000);        
    ds.setMaxIdle(10);
    ds.setInitialSize(10);
    ds.setMinEvictableIdleTimeMillis(30000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM