jdbcTemplate.queryForObject(sql, params, new UserVote()); // 一个对象
jdbcTemplate.query(sql, new Object[] { id }, new UserVote()); // 一个list
这个地方的 UserVote需要实现implements RowMapper<UserVote> 进而实现方法public UserVote mapRow(ResultSet rs, int rowNum) throws SQLException
在里面进行手动映射。
/**
*
* JdbcTemplate 映射方法
*/
@Override
public UserVote mapRow(ResultSet rs, int rowNum) throws SQLException {
UserVote userVote = new UserVote();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String strDate = rs.getString("create_time");
Date date = null;
try {
date = sdf.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
userVote.setCreateTime(date); // 可以直接写成rs.getDate()
userVote.setId(rs.getString("id"));
return userVote; // 并不能直接return this.会导致一直返回同一个对象
}
注意,实现 RowMapper 是可以返回一个对象,和一个list的,而在mapRow 方法中,只需要反回一个对象即可
2016年1月27日 17:59:05
可以不用实现RowMapper,使用
即可。BeanPropertyRowMapper.newInstance(A.class)
另外,jdbcTemplate可以做数据库列名到Java驼峰式的转换,例如:s_name 可以自动转到 sName。