在 Spring 中使用多个数据源

发布于 2025-01-16 18:53:53 字数 7216 浏览 0 评论 0原文

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

下面是代码:

DbConfig 类:

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

数据类:

    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 类:

    <!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 响应和显示答案类:

    <!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 中存在的电话号码,当我询问时收到了答案数据库 B 它没有给我任何结果。今天我进行了构建和清理,当我查询数据库 B 时,它给了我响应,但数据库 A 没有给我答案,它没有给我任何结果。我不明白它如何以及为什么不能同时连接到两个数据库。谢谢

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.

Here is the code:

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:

    @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:

@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:

    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:

    <!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:

    <!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. 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. I do not understand how and why it does not connect to both databases at once. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

节枝 2025-01-23 18:53:54

为配置类中的每个数据源创建一个 JdbcTemplate。然后,将这些 JdbcTemplate bean 注入适当的 Repository 类。

除了配置类之外,您不应该实例化由 Spring 管理的类。

Create a JdbcTemplate for each Datasource in your config class. Then, inject those JdbcTemplate beans into the appropriate Repository class.

You should not be instantiating classes that are managed by Spring, except in config classes.

天邊彩虹 2025-01-23 18:53:54

您必须将数据源注入到 Repository 类中。如果您调用 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

You have to inject datasource to Repository class. If you call db.getDatasource() then each call creates datasource.

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. It creates bean in spring context

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文