jdbcTemplate.queryForObject 方法注意

正确方法:

String sql = "select ID from Structures(nolock) where id=?";
Integer ret = jdbcTemplate.queryForObject(sql, Integer.class, new Object[]{id});

错误方法:

String sql = "select ID from Structures(nolock) where id=?";
int ret = jdbcTemplate.queryForObject(sql, int.class, new Object[]{id});

String sql = "select * from Structures(nolock) where id=?";
Structure ret = jdbcTemplate.queryForObject(sql, Structure.class, new Object[]{id});
源代码:

public  T queryForObject(String sql, Class requiredType, Object... args) throws DataAccessException {
	return queryForObject(sql, args, getSingleColumnRowMapper(requiredType));
}

错误分析:queryForObject此重装第2个参数Class requiredType只能是基本数据类型的封装类,如Integer、String

正确方法:

String sql = "select * from Structures(nolock) where id=?";
jdbcTemplate.queryForObject(sql,new Object[]{id},new BeanPropertyRowMapper(Structure.class));

源代码:

public  T queryForObject(String sql, Object[] args, RowMapper rowMapper) throws DataAccessException {
	List results = query(sql, args, new RowMapperResultSetExtractor(rowMapper, 1));
	return DataAccessUtils.requiredSingleResult(results);
}
或者继承queryForObject此实现第3个参数接口RowMapper rowMapper的类,例如:

public class UserInfo implements RowMapper, Serializable {
        private Integer id; 
	private String name;
	@Override
    	public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
        	UserInfo userInfo = new UserInfo();
        	userInfo.setId(rs.getInt(id));
        	userInfo.setUname(rs.getString(uname));
        	userInfo.setUnumber(rs.getInt(unumber));
        	userInfo.setuRegisterTime(rs.getDate(uregister_time));
        	return userInfo;
    	}
}

简单方法不在类上实现接口:

		String sql = "select GoodComments,BadComments,UseCount from Structures(nolock) where id=?";
		return jdbcTemplate.queryForObject(sql, new RowMapper(){
			@Override
			public Structure mapRow(ResultSet rs, int rowNum) throws SQLException{
				Structure structure = new Structure();
				structure.setGoodComments(rs.getInt("GoodComments"));
				structure.setBadComments(rs.getInt("BadComments"));
				structure.setUseCount(rs.getInt("UseCount"));
				return structure;
			}
		}, id);



你可能感兴趣的:(java)