Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapsqlparametersource vs java.util.map

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);
}
like image 540
Punter Vicky Avatar asked Feb 28 '26 10:02

Punter Vicky


1 Answers

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

like image 80
Federico Piazza Avatar answered Mar 03 '26 02:03

Federico Piazza