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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With