I read in spring documentation that MapSqlParameterSource is just a wrapper over Map. What is the advantage of using MapSqlParameterSource instead of 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:
private final Map<String, Object> values = new LinkedHashMap<String, Object>();
There are not actually considerable benefits of using a map or spring provided implementation.
If you dig a little on the code, you can use addValue
, below the code:
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("a", 1).addValue("b", 2)...
So, it's just a matter of taste to use Map
or MapSqlParameterSource
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.