在 Spring 中使用多个数据源

Using multiple DataSources in Spring

我在 Spring 中构建了一个网络应用程序。到目前为止,我只能连接到一个数据源,但我需要连接到两个数据源。

代码如下:

DbConfig 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
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
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;
    
} }

控制器:

@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";
}}

数据class:

    import lombok.Data;


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

百里香叶 index.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 响应并显示答案 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>

昨天我询问了一个存在于数据库 A 中的 phone 号码,我收到了答复,当我询问数据库 B 时没有得到任何结果。今天我做了一个构建和清理,当我查询数据库 B 时,它给了我一个响应,但是数据库 A 没有给我一个答案,它没有给我任何结果。我不明白它如何以及为什么不同时连接到两个数据库。谢谢

为配置中的每个数据源创建一个 JdbcTemplate class。然后,将那些 JdbcTemplate beans 注入到适当的 Repository class.

您不应实例化由 Spring 管理的 classes,配置 classes 除外。

您必须将数据源注入存储库 class。如果您调用 db.getDatasource(),则每次调用都会创建数据源。

class Repository{

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

您可以简单地使用@Bean 注释方法注入bean。它在 spring 上下文

中创建 bean