2017-04-10 87 views
0

在我的JDBC培訓中,我對使用where子句有疑問。java Spring JDBCTemplate - where子句

假設我在我的db中有一個表,我想用一個使用jdbc模板的彈簧應用程序來管理,讓我們假設「Logbase」與此列:host,user,clientip。假設現在我想允許基於所有列一列的查詢數據庫,即:

Select * from Logbase where host = x 

Select * from Logbase where user = y 

Select * from Logbase where clientip = z 

我想我必須寫一個分離Java方法爲每個此查詢,如下所示:

public Logbase getLogbaseFromHost(String id) 
     { 
      String SQL = "select * from Logbase where host = ?"; 
      Logbase logbase = (Logbase) jdbcTemplate.queryForObject(SQL, new Object[]{id}, 
        (rs, rowNum) -> new Logbase(rs.getString("host"), rs.getString("user"), 
        rs.getInt("clientip"))); 

      return logbase; 
     } 



public Logbase getLogbaseFromUser(String id) 
     { 
      String SQL = "select * from Logbase where user = ?"; 
      Logbase logbase = (Logbase) jdbcTemplate.queryForObject(SQL, new Object[]{id}, 
        (rs, rowNum) -> new Logbase(rs.getString("host"), rs.getString("user"), 
        rs.getInt("clientip"))); 

      return logbase; 
     } 




public Logbase getLogbaseFromClientIP(String id) 
      { 
       String SQL = "select * from Logbase where clientip = ?"; 
       Logbase logbase = (Logbase) jdbcTemplate.queryForObject(SQL, new Object[]{id}, 
         (rs, rowNum) -> new Logbase(rs.getString("host"), rs.getString("user"), 
         rs.getInt("clientip"))); 

       return logbase; 
      } 

現在,如果我想允許基於2個參數的查詢數據庫,我想我必須爲3個可能的參數對(一個用於clientip用戶,另一個用於clientip主機和最後一個用戶主機)編寫一個方法。

最後,如果我想要允許查詢數據庫選擇所有參數,我必須寫請求所有變量的查詢中的where子句的另一個方法。

如果我沒有說異端邪說,一切都是正確的,我有7種方法。但是,我參數和組合的數量增加了,這可能是一個問題。有辦法解決它嗎?

注意:出於工作原因,我不能使用Hibernate或其他ORM框架。我必須使用jdbc。

Tnx給所有的耐心和迴應。

回答

0

該溶液可以是基於SQL

Select * 
from Logbase 
where 
    (? is null or host = ?) 
    AND (? is null or user = ?) 
    AND (? is null or clientip = ?) 

jdbcTemplate.queryForObject(SQL,新的對象[] {主機,主機,用戶,用戶,clienttip,clienttip}

因此,例如,如果是user未指定(用戶爲空 - 真)的所有記錄都包含

+0

斯坦尼斯感謝,我會嘗試。我不明白一件事:爲什麼在queryForObject方法的調用中,我們每次寫入變量2次? Thas是,爲什麼{host,host,user,user,clienttip,clienttip}而不是{host,user,clienttip}? –

+0

我們在SQL中有6個參數,所以我們必須提供6個值。想象一下,我們將每個替代?帶有一個參數 – StanislavL

+0

Tnx,一目瞭然。我非常感激。 –

0

所以,你也可以使用org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate

** Select * 
    from Logbase where 
     (:host is null or host = :host) 
     AND (:user is null or user = :user) 
     AND (:clientip is null or clientip = :clientip)** 

和Java代碼:

 MapSqlParameterSource params = new MapSqlParameterSource(); 
     params.addValue("host", host); 
     params.addValue("user", user); 
     params.addValue("clientip", clientip); 
     namedParameterJdbcTemplate.queryForObject(sqlQuer, params);