2017-04-10 89 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);