Spring 中的jdbcTemplate 封装对象

 
   
 
   

第一种方式 :带参数的封装方式

Actor actor = this.jdbcTemplate.queryForObject( "select first_name, last_name from t_actor where id = ?", new Object[]{1212L}, new RowMapper() { public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { Actor actor = new Actor(); actor.setFirstName(rs.getString("first_name")); actor.setLastName(rs.getString("last_name")); return actor; } });

 


 
   
 
   

第二种方式:未带输入参数的 封装方式 匿名类

 

List actors = this.jdbcTemplate.query(
        "select first_name, last_name from t_actor",
        new RowMapper() {
            public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
                Actor actor = new Actor();
                actor.setFirstName(rs.getString("first_name"));
                actor.setLastName(rs.getString("last_name"));
                return actor;
            }
        });


 
   

第三种:内部私有类的方式

public List findAllActors() {
    return this.jdbcTemplate.query( "select first_name, last_name from t_actor", new ActorMapper());
}

private static final class ActorMapper implements RowMapper {

    public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
        Actor actor = new Actor();
        actor.setFirstName(rs.getString("first_name"));
        actor.setLastName(rs.getString("last_name"));
        return actor;
    }
}

 
   
 
   

第四种方式:

public Actor findActor(String specialty, int age) {
    String sql = "select id, first_name, last_name from T_ACTOR" +
            " where specialty = ? and age = ?";
    RowMapper mapper = new RowMapper() {
        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;
        }
    };
    // notice the use of varargs since the parameter values now come
    // after the RowMapper parameter
    return this.simpleJdbcTemplate.queryForObject(sql, mapper, specialty, age);
}

四种方式,仅供参考

你可能感兴趣的:(Spring)