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)}); }