Nadra
Nadra

Reputation: 13

How to create custom datasource for each session

I would like to create a stateless bean in Spring boot which enable user to connect to a specific database, so I started with this code, but i'm still new with spring boot.

@Bean
@Primary 
public DataSource helloDataSource() {

    return DataSourceBuilder.create()
            .username("myUsername")
            .password("myPassword")
            .driverClassName("myDBDriver")
            .build();
}

So what is the best way to follow to make this code work and connect to any database ( Also remote Database )

Upvotes: 1

Views: 512

Answers (1)

Prashant
Prashant

Reputation: 5383

There are several ways that this could be done. One of my preferred way is to provide configuration of data sources via properties file. Here is a sample property file for postgresql:

pg.datasource.url=jdbc:postgresql://db-server-bar:5432/app-db
pg.datasource.username=root
pg.datasource.password=toor
pg.datasource.driver-class-name=org.postgresql.Driver

Now you can create configuration class for each datasource:

public class BarDbConfig {

  @Bean(name = "pgDataSource")
  @ConfigurationProperties(prefix = "pg.datasource")
  public DataSource dataSource() {
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "barEntityManagerFactory")
  public LocalContainerEntityManagerFactoryBean 
  barEntityManagerFactory(
    EntityManagerFactoryBuilder builder,
    @Qualifier("pgDataSource") DataSource dataSource
  ) {
    return
      builder
        .dataSource(dataSource)
        .packages("com.app.domain")
        .persistenceUnit("pg")
        .build();
  }
}

For a detailed tutorial, you can refer to this tutorial.

There can also be situations where you would like to switch databases at runtime. In which case, you can use something called AbstractRoutingDataSource. A detailed tutorial on how to use this feature can be found at Spring's official blog site.

Upvotes: 1

Related Questions