springJDBC queryForObject结果转bean对象

使用queryForObject 查找对应对象时, 如查找person,beanperson

Person person = (Person) this.getJdbcTemplate().queryForObject("select * from person where id="+id, Person.class);

Spring并不知道如何将结果转成Person.class

 

所以需要写一个Person RowMapper 继承RowMapper接口 ,如:

PersonRowMapper implements RowMapper {

public Object mapRow(ResultSet rs, int value) throws SQLException {
Person person = new Person ();
person.setId(new Integer(rs.getInt("id")));
person.setUsername(rs.getString("username"));
person.setAge(rs.getString("age"));
return user;
}
}

 

然后就可以得到person对象(查找结果唯一),如:

Person person = (Person) this.getJdbcTemplate().queryForObject("select * from person where id="+id,new PersonRowMapper());

 

 

你可能感兴趣的:(spring,bean)