mapsql参数源与java.util.map
mapsqlparametersource vs java.util.map
我在 spring 文档中读到 MapSqlParameterSource 只是 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);
}
MapSqlParameterSource
只是一个LinkedHashMap
的装饰器,如果你查看MapSqlParameterSource
,你会看到:
private final Map<String, Object> values = new LinkedHashMap<String, Object>();
使用地图或 spring 提供的实现实际上并没有很大的好处。
如果你稍微研究一下代码,你可以使用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
returns 相同的对象,您可以使用(如果愿意)进行流畅的方法调用,例如:
.addValue("a", 1).addValue("b", 2)...
所以,使用 Map
或 MapSqlParameterSource
只是个人喜好问题
我在 spring 文档中读到 MapSqlParameterSource 只是 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);
}
MapSqlParameterSource
只是一个LinkedHashMap
的装饰器,如果你查看MapSqlParameterSource
,你会看到:
private final Map<String, Object> values = new LinkedHashMap<String, Object>();
使用地图或 spring 提供的实现实际上并没有很大的好处。
如果你稍微研究一下代码,你可以使用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
returns 相同的对象,您可以使用(如果愿意)进行流畅的方法调用,例如:
.addValue("a", 1).addValue("b", 2)...
所以,使用 Map
或 MapSqlParameterSource