lorenzo1723
lorenzo1723

Reputation: 69

How do I write in two different databases in Spring Boot?

I need to make a REST API so two components can communicate with each other. Basic draw of the service

The flow starts like this:

  1. Component 1 sends a request
  2. The API processes it and, if everything's correct, writes inside Component 2 DB
  3. Various data processing...
  4. Component 2 sends a request
  5. The API processes it and, if everything's correct, writes inside Component 1 DB

How do I make this appen in Spring Boot? I don't need any domain class, so I don't think I need to use JPA.

Update: I need to make it work with JdbcTemplate

Thanks in advance

Upvotes: 1

Views: 1019

Answers (1)

Eteka Christopher
Eteka Christopher

Reputation: 123

I'm not sure what you intend to achieve here but this is what I would suggest you do if you really need to achieve this with JDBC template.

  1. In your configuration file: e.g application.properties, you could specify keys to hold values used in configuring every different connection to the databases you need to interact with. A naive example could be:
app.datasource1.url=...
app.datasource1.driver=...
app.datasource1.username=...
app.datasource1.password=...

app.datasource2.url=...
app.datasource2.driver=...
app.datasource2.username=...
app.datasource2.password=...
  1. You could create beans of these connections in a config class and differentiate them with names (qualifiers), one of them could be a tagged primary data source and the other a secondary data source. As an alternative, however, you can do 3 each time you need an instance of the DB connection.

  2. Since you are using the JDBC template, in the service classes or implementations where you make calls to the database, you could start first by creating a connection (an instance of JDBC Template) before using it.

With this approach, you can create as many connections as you want to as many DB as you want. Don't know if this helps.

Upvotes: 1

Related Questions