今天随便翻了翻spring2.0的文档,发现了许多非常近似.net的功能,这大大提高了对数据操作的准确性
看看下面这段代码

public int countOfActorsByFirstName(String firstName) ...{
String sql = "select count(0) from T_ACTOR where first_name =?";
Object[] obj=new Object[1];
obj[0]=firstName;
return template.queryForInt(sql, obj);
}这段代码是没有参数支持前的用法。"?"作为参数时需要你在object中格外小心参数的顺序,这一点很令人讨厌

public int countOfActorsByFirstName(String firstName) ...{
String sql = "select count(0) from T_ACTOR where first_name = :first_name";
NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(this.getDataSource());
Map namedParameters = new HashMap();
namedParameters.put("first_name", firstName);
return template.queryForInt(sql, namedParameters);
}看看Spring2.0中新添加的参数支持功能,这个在java中可望而不可及的功能被实现了!我觉得这一点真的很重要,不但加快了开发速度而且还大大的减少了错误的发生机率。
接下来的代码则是用了java5的特性给我们带来的方便

public Actor findActor(long id) ...{
String sql = "select id, first_name, last_name from T_ACTOR where id = ?";

ParameterizedRowMapper<Actor> mapper = new ParameterizedRowMapper()<Actor> ...{
// notice the return type (c.f. Java 5 covariant return types)
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException ...{
Actor actor = new Actor();
actor.setId(rs.getLong("id"));
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
};
// again, normally this would be dependency injected of course...
SimpleJdbcTemplate simpleJdbcTemplate = new SimpleJdbcTemplate(this.getDataSource());
return simpleJdbcTemplate.queryForObject(sql, mapper, id);
}而没有这个特性以前的代码则是这个样子的

public Actor findActor(long id) ...{
String sql = "select id, first_name, last_name from T_ACTOR where id = ?";

RowMapper mapper = new RowMapper() ...{

public Object mapRow(ResultSet rs, int rowNum) throws SQLException ...{
Actor actor = new Actor();
actor.setId(rs.getLong(Long.valueOf(rs.getLong("id"))));
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
};
// normally this would be dependency injected of course...
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.getDataSource());
// notice the cast, and the wrapping up of the 'id' argument
// in an array, and the boxing of the 'id' argument as a reference type
return (Actor) jdbcTemplate.queryForObject(sql, mapper, new Object[] ...{Long.valueOf(id)});
}使用了SimpleJdbcTemplate,这样代码显得更加清晰。
Spring2.0真的很好
本文介绍了Spring2.0中的新特性,特别是针对数据库操作的支持,包括参数支持、使用Java5特性的代码示例,以及这些改进如何提高开发效率和减少错误。
4万+

被折叠的 条评论
为什么被折叠?



