user123959
user123959

Reputation: 1256

Spring boot how to add a second datasource that may or may not exist

I want to have an optional secondary database for my application such that if the secondary database exists on the deployed environment a repository can retrieve data from it, but if it does not exist, the application will still work fine with just the primary database, and the repository will behave in a way where the application can know this datasource isn't available.

I can definitely think of ways of accomplish this type of thing, but I wonder if there is a more direct configuration type way of achieving this. Or if there is a pattern type way of handling that is preferable.

Upvotes: 2

Views: 2820

Answers (1)

You can certainly work with multiple databases in a clean way by just implementing 2 database configurations and annotating one of them with @Primary annotation.

@Bean(name = "mainDataSource")
@Primary
public DataSource mainDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}

And for the secondary database, you can create pretty much the same, but don't put the @Primary annotation on it.

@Bean(name = "secondaryDataSource") 
public DataSource secondaryDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}

Note that you don't need to put the @Primary annotation just on the DataSource bean, but in any bean you use to connect to your database.

After doing this, all you have to do is annotate your EntityManager or any other connection manager you normally use with the @Qualifier.

@Autowired
@Qualifier("mainEntityManager")
private EntityManager mainDatabase;

@Autowired
@Qualifier("secondEntityManager")
private EntityManager secondDatabase;

In my case, I prefer to make a class to manage this on the backstage. You can find a complete example of this on my article on linkedin. and check out the example code on GitHub

Upvotes: 5

Related Questions