简体   繁体   中英

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. 服务的基本绘制

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

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: eg 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.

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