Multiple Databases with Spring Boot

Asked

Viewed 735 times

1

In my application, customers have their own database and I am developing a REST application, with Spring Boot, from which I need to configure Datasources to connect to databases, according to a Pathparam URL, in Runtime.

Someone knows how to do it?

I researched about Abstractroutingdatasource and Multi-tenant, but I could not understand how it works very well.

If anyone can help me... even to give me a north hehe, so I can implement all this correctly :)

Thank you in advance!

2 answers

0

If you want to create a new Datasource at runtime, you can use the Datasourcebuilder.

This class provides an enormous flexibility and ease, an example of use is the following:

public DataSource buildDatasource(String url, String username, String password) {
    return DataSourceBuilder.create().url(url).username(username).password(password).build();
}

Just remember that you need to have the drivers for the banks you want to connect to available in your application or server, in case you are curious how it works just look at the source code of the class

0

I suggest you read the article of this blog that exemplifies the configuration of for spring-boot application to work with two databases.

In short, this would be the sequence of activities to be carried out:

  1. Configure the connection data of the two banks in the application.properties;
  2. create entity and repository classes for each database; and
  3. Create a configuration class for each database (take some of the automation of Spring Boot, so we have more control of what is happening and, consequently, we can inform each package connected to each BD).

The author also points out that at the end it is necessary to note the methods of at least one of the configuration classes with the Annotation @Primary, to inform that this is the primary or principal bank of the application.

  • Diego, thank you so much for answering. But in this case that you described, I would have the databases already pre-defined, right? However, in the actual case of my application, each client has its own database, that is, if I register a new client, a BD will be generated for it as well. Hence, the loading of these data would have to be dynamic

  • @Pauloaugusto - I think I understand what you need. Look at this video that talks about the Multitenancy Implementation by Hibernate schema from Algaworks: link

Browser other questions tagged

You are not signed in. Login or sign up in order to post.