public <T> T queryForObject(String sql, @Nullable Object[] args, RowMapper<T> rowMapper)
其中RowMapper泛型接口定义了ResultSet var1, int var2这个两个参数,
我们在使用ResultSet类型参数的时候,不要像写jdbc那样进行rs.next()进行判断,因为JdbcTemplate底层已经帮我做了这件事了,正确用法如下:
public User getUserByEmil(String email){
return jdbcTemplate.queryForObject("select * from users where email = ?",new Object[]{email},
(ResultSet rs,int rowNum) -> { // 直接给出ResultSet已经移动了指针
return new User(
rs.getLong("id"),
rs.getString("name"),
rs.getString("email"),
rs.getString("password")
);
});
}
不正确用法如下,你会永远得到null:
public User getUserByEmil(String email){
return jdbcTemplate.queryForObject("select * from users where email = ?",new Object[]{email},
(ResultSet rs,int rowNum) -> {
if(rs.next()){
return new User(
rs.getLong("id"),
rs.getString("name"),
rs.getString("email"),
rs.getString("password")
);
}else{
return null;
}
});
}