如何在JPA中连接多个数据库?

时间:2020-03-23 14:49:09

标签: java database spring-boot jpa spring-data-jpa

我有一个Spring Boot应用程序,该应用程序当前正在使用JPA连接到单个数据库。其application.properties文件中的连接详细信息:

spring.datasource.url=jdbc:oracle:thin:@localhost:1522:orcl
spring.datasource.username=example
spring.datasource.password=example
spring.datasource.driver.class=oracle.jdbc.driver.OracleDriver

现在我有一个要连接的新数据库,因此我的应用程序现在可以连接2个数据库。我可以使用JDBC连接它,在那里我将不得不手动编写连接代码。

我一直在寻找解决方案。有些处于休眠状态,其中包含多个配置文件。其他人正在使用JDBC。

我尝试在spring docs中寻找是否有规定在application.properties文件中定义多个数据源,但是找不到任何东西。

我想知道是否存在仅使用JPA的解决方案。谢谢您的时间。

2 个答案:

答案 0 :(得分:1)

请遵循以下步骤:

  1. 将其他数据源配置添加到您的 application.properties。

  2. 在application.properties中将SQL方言设置为“ default”。 让Spring自动检测每个数据源的不同SQL方言

  3. 使用两个嵌套包为每个数据源创建一个Java包
  4. 为第一个数据库创建配置类
  5. 为第二个数据库创建配置类
  6. 为第一个数据库创建实体
  7. 为第一个数据库创建存储库
  8. 为第二个数据库创建实体
  9. 为第二个数据库创建存储库

此处提供完整代码,

https://github.com/jahe/spring-boot-multiple-datasources

本教程中采取了以上步骤

https://medium.com/@joeclever/using-multiple-datasources-with-spring-boot-and-spring-data-6430b00c02e7

希望这会有所帮助:)

答案 1 :(得分:0)

app.post('/login' , jsonParser , function(req, resp)
{

  var username= req.body.username;
  var password = req.body.password;

  connection.query('SELECT * FROM users WHERE username = ?',[username], function (error, results, fields) {
  if (error) {
    // console.log("error ocurred",error);
    resp.send({
      "cod+hgee":400,
      "failed":"error ocurred"
    })
  }else{

    if(results.length >0){
      console.log(results[0]);
      if(results[0].Password == password){
        resp.send({
          code : "200",
          "success":"login sucessfull"
            });
      }
      else{
        resp.send({
          code:"202",
          "success":"Email and password does not match"
            });
      }
    }
    else{
      resp.send({
        code:"204",
        "success":"Email does not exits"
          });
    }
  }
  });
});