2017-03-02 30 views
0

我在Spring的文檔中看到,MapSqlParameterSource只是Map上的一個包裝器。使用MapSqlParameterSource而不是Map的優點是什麼?mapsqlparametersource vs java.util.map

public int countOfActorsByFirstName(String firstName) { 

    String sql = "select count(*) from T_ACTOR where first_name = :first_name"; 

    SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName); 

    return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class); 
} 




public int countOfActorsByFirstName(String firstName) { 

    String sql = "select count(*) from T_ACTOR where first_name = :first_name"; 

    Map<String, String> namedParameters = Collections.singletonMap("first_name", firstName); 

    return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class); 
} 
+0

目前什麼都沒有。當您有可能使用不支持泛型的Java版本時,遺留下來的遺留問題仍然存在。 – Kayaman

+1

由於javadoc顯示:一個流暢的API來填充參數,可以指定參數的SQL類型。 –

回答

1

MapSqlParameterSource只是一個LinkedHashMap的裝飾,如果你檢查MapSqlParameterSource,你會看到:

private final Map<String, Object> values = new LinkedHashMap<String, Object>(); 

有沒有實際使用提供的實現地圖或彈簧的可觀的效益。

如果你挖的代碼一點,你可以使用addValue,下面的代碼:

public MapSqlParameterSource addValue(String paramName, Object value) { 
    Assert.notNull(paramName, "Parameter name must not be null"); 
    this.values.put(paramName, value); 
    if (value instanceof SqlParameterValue) { 
     registerSqlType(paramName, ((SqlParameterValue) value).getSqlType()); 
    } 
    return this; 
} 

所以,你可以看到,addValue返回相同的對象,你可以用它(如果你喜歡)做流利的方法調用,如:

.addValue("a", 1).addValue("b", 2)... 

所以,它只是一個品味的問題使用MapMapSqlParameterSource

+0

使用MapSqlParameterSource的缺點是缺少構造函數'new MapSqlParameterSource(MapSqlParameterSource)'。 I. e。你不能重用已經設置的參數。例如,在創建報表時,我想重複使用具有不同附加參數的多個語句的句點的開始日期和結束日期。在這種情況下,我必須使用傳統的地圖,所以我可以這樣做:'新的MapSqlParameterSource(periodParams).addValue(「additionalParam」,foobar);' –

相關問題