简体   繁体   English

mapsqlparametersource与java.util.map

[英]mapsqlparametersource vs java.util.map

I read in spring documentation that MapSqlParameterSource is just a wrapper over Map. 我在春季文档中读到,MapSqlParameterSource只是Map的包装。 What is the advantage of using MapSqlParameterSource instead of Map? 使用MapSqlParameterSource而不是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);
}

The MapSqlParameterSource is just a decorator of a LinkedHashMap , if you check the MapSqlParameterSource , you will see this: MapSqlParameterSource只是LinkedHashMap的装饰器,如果您检查MapSqlParameterSource ,则会看到以下内容:

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

There are not actually considerable benefits of using a map or spring provided implementation. 使用map或spring提供的实现实际上并没有明显的好处。

If you dig a little on the code, you can use addValue , below the code: 如果您对代码addValue ,可以在代码下方使用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;
}

So, as you can see, addValue returns the same object, which you can use (if you like) to do fluent method calls, like: 因此,如您所见, addValue返回相同的对象,您可以使用该对象(如果您愿意)进行流畅的方法调用,例如:

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

So, it's just a matter of taste to use Map or MapSqlParameterSource 因此,使用MapMapSqlParameterSource只是个好MapSqlParameterSource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM