简体   繁体   English

在 Spring 中使用多个数据源

[英]Using multiple DataSources in Spring

I have built a web app in Spring. Till now I have managed to connect to only one datasource but I need to connect to two Datasources.我在 Spring 中构建了一个 web 应用程序。到目前为止,我只能连接到一个数据源,但我需要连接到两个数据源。

Here is the code:这是代码:

DbConfig class:数据库配置 class:

 @Configuration
public class DbConfig {
    
    @Bean
    @Primary
    public DataSource dataSourceMail() {
    
       
            
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("oracle.jdbc.OracleDriver");
        config.setJdbcUrl("jdbc:oracle:thin:@1");
        config.setUsername("xxx");
        config.setPassword("xxx");
        config.setConnectionTimeout(20000);
        config.setMaximumPoolSize(100);
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        
        
        return new HikariDataSource(config);
    }
    
    @Bean(name="inregIvg")
    public DataSource dataSourceInregIvg() {
        
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("oracle.jdbc.OracleDriver");
        config.setJdbcUrl("jdbc:oracle:thin:@2");
        config.setUsername("yyy");
        config.setPassword("yyy");
        config.setConnectionTimeout(20000);
        config.setMaximumPoolSize(100);
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        
        
        return new HikariDataSource(config);
        
    }
}

Repository:存储库:

    @Repository
public class TelefonMailRepository {
      
    
    
  
    
    public List<Map<String, Object>> findByNumber(String telefon){
        DbConfig dbc = new DbConfig();
        
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dbc.dataSourceInregIvg());
    List<Map<String, Object>> info1 = jdbcTemplate.queryForList("select cif, den_client from b101_conturi where telefon=?", telefon);
   
   return info1;
    
    }
    
    
    
    public Map<String, Object> findByNumber2(String telefon) {
        
        DbConfig dbc = new DbConfig();
        
        String query2 = "select cnp, nume, prenume from utilizatori where telefon=?";
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dbc.dataSourceMail());
        Map<String, Object> info = jdbcTemplate.queryForMap(query2,telefon);
        
        return info;
                
    } }

Service:服务:

    @Service
public class TelefonMailService {
    
@Autowired    
private TelefonMailRepository repository;



public List<Map<String, Object>> getRaspuns(String telefon) {
   
    
    List<Map<String, Object>> mapList = new ArrayList<>();

    
    
mapList = repository.findByNumber(telefon);

    return mapList;
 
}

public Raspuns getRaspunsB(String telefon) {
    
    Map<String, Object> map = repository.findByNumber2(telefon);
    
    String cnp = (String)map.get("cnp").toString();
    String nume = (String)map.get("nume");
    String prenume = (String)map.get("prenume");
    
    Raspuns raspuns = new Raspuns();
    raspuns.setCnp(cnp);
    raspuns.setNume(nume);
    raspuns.setPrenume(prenume);
    
    return raspuns;
    
} }

Controller: Controller:

@PostMapping("/raspuns")
public String postDbRequest(@RequestParam("text2")String telefon, Model model) {

    Raspuns x = service.getRaspunsB(telefon);
    model.addAttribute("raspuns", x);
 
  
   List<Map<String, Object>> mapList = service.getRaspuns(telefon);
    model.addAttribute("map_list",mapList);
 
  
    
   
    return "raspuns";
}}

Data class:数据 class:

    import lombok.Data;


@Data
public class Raspuns {
    
 private String cnp;
   
 private String nume;
   
 private String prenume;
 
 private String cif;
 
 private String den_client;
    
}

Thymeleaf index.html class: Thymeleaf 索引.html class:

    <!DOCTYPE html>
<html xmlns:th ="http://www.thymeleaf.org" >
<head>
<meta charset ="UTF-8" ></meta>
<meta name ="viewport" content ="width=device-width, initial-scale=1, shrink-to-fit=no" >
<!-- Read CSS -->
<link rel ="stylesheet" th:href ="@{/webjars/bootstrap/css/bootstrap.min.css}" >
<link rel ="stylesheet" th:href ="@{/stil.css}" >
<!-- Read JS -->
<script th:src ="@{/webjars/jquery/jquery.min.js}" defer ></script>
<script th:src ="@{/webjars/bootstrap/js/bootstrap.min.js}" defer ></script>
<title> Cautare telefon sau e-mail</title>
</head>
<body class ="bg-light" >
    <h2 text-align="center">Cautare telefon sau email</h2>
<div class ="text-center" >
<form method ="post" action ="/raspuns" >
<div class="form-group">
    <input type ="number" minlength="10" maxlength="10" class="form-control" name ="text2" th:value ="${text2_value}" placeholder="Numar telefon"/>
    
    <input type ="submit" value ="Cauta" class ="btn btn-primary" margin-top="2%"/>
</div>
    </form>
    <br></br>
<form method ="post" action ="/raspuns2" >
    <div class ="form-group" >
<input type ="email" class ="form-control" placeholder ="Adresa email" th:value="${email_value}"
name ="email" />

<input type ="submit" value ="Cauta" class ="btn btn-primary" margin-top="2%"/>
</div>
    
</form>

</div>
   
</body>
</html>

Thymleaf html response and display answer class: Thymleaf html 响应并显示答案 class:

    <!DOCTYPE html>
<html xmlns:th ="http://www.thymeleaf.org" >
<head>
<meta charset ="UTF-8" ></meta>
<meta name ="viewport" content ="width=device-width, initial-scale=1, shrink-to-fit=no" >
<!-- Read CSS -->
<link rel ="stylesheet" th:href ="@{/webjars/bootstrap/css/bootstrap.min.css}" >
<link rel ="stylesheet" th:href ="@{/stil.css}" >
<!-- Read JS -->
<script th:src ="@{/webjars/jquery/jquery.min.js}" defer ></script>
<script th:src ="@{/webjars/bootstrap/js/bootstrap.min.js}" defer ></script>
<title> Cautare telefon sau email</title>
</head>
<body>
    <form  action="/">
    <button class ="btn btn-primary">Acasa</button>    
    </form>
<h1> Cautare telefon</h1>

<table class="table">
    
  <tbody>
    <tr th:each="map : ${map_list}" >
<td> CNP:</td>
<td th:text ="${map.get('cif')}" ></td>
<td> Nume:</td>
<td th:text ="${map.get('den_client')}" ></td>
</tr>




  </tbody>
</table>
<table>
<tr>
<td> CNP:</td>
<td th:text ="${raspuns.cnp}" ></td>
</tr>
<tr>
<td> Nume:</td>
<td th:text ="${raspuns.nume}" ></td>
</tr>
<tr>
<td> Prenume:</td>
<td th:text ="${raspuns.prenume}" ></td>
</tr>
</table>

</body>
</html>

Yesterday I interogated a phone number that exists in database A and I received answer and when I interogated database B it gave me no results.昨天我询问了一个存在于数据库 A 中的电话号码,我收到了答复,当我询问数据库 B 时,它没有给我任何结果。 Today I did a build and clean and when I interogated database B it gave me a response but from database A did not give me an answer it gave me no results.今天我做了一个构建和清理,当我查询数据库 B 时,它给了我一个响应,但是数据库 A 没有给我一个答案,它没有给我任何结果。 I do not understand how and why it does not connect to both databases at once.我不明白它如何以及为什么不同时连接到两个数据库。 Thanks谢谢

Create a JdbcTemplate for each Datasource in your config class. Then, inject those JdbcTemplate beans into the appropriate Repository class.在您的配置 class 中为每个数据源创建一个 JdbcTemplate。然后,将这些 JdbcTemplate beans 注入适当的存储库 class。

You should not be instantiating classes that are managed by Spring, except in config classes.您不应实例化由 Spring 管理的类,配置类除外。

You have to inject datasource to Repository class. If you call db.getDatasource() then each call creates datasource.您必须将数据源注入存储库 class。如果调用 db.getDatasource(),则每次调用都会创建数据源。

class Repository{

   private final Datasource dtSource;
   private final JdbcTemplate jdbcTemplate;
   public Repository(@Qualifier("mydatasource") Datasource dtSource){
      This.jdbcTemplate = new JdbcTemplate(dtSource);
   }
}

Simply you can inject beans with @Bean annotated method.只需使用 @Bean 注释方法注入 bean。 It creates bean in spring context它在 spring 上下文中创建 bean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM