JdbcTemplate queryForObject Incorrect result size: expected 1, actual 0

在开发中,遇到使用Spring中的jdbcTemplate 时,通过唯一条件查询不到结果时返回Incorrect result size: expected 1, actual 0.

java代码:

@Override  
  public  T queryForObject(String sql, RowMapper rowMapper, Object... args) throws DataAccessException {  
   List results = query(sql, args, new RowMapperResultSetExtractor(rowMapper, 1));  
            return DataAccessUtils.requiredSingleResult(results);  
        }  

 DataAccessUtils.requiredSingleResult(results);这个方法

public static  T requiredSingleResult(Collection results) throws      IncorrectResultSizeDataAccessException {  
       int size = (results != null ? results.size() : 0);  
       if (size == 0) {  
            throw new EmptyResultDataAccessException(1);  
       }  
       if (results.size() > 1) {  
            throw new IncorrectResultSizeDataAccessException(1, size);  
          }  
            return results.iterator().next();  
        }  

结果返回0和大于一个都会抛出异常,我们使用这个方法是期望返回一个对象的,但是可能返回0,我们需要的是null而不是异常,可以使用DataAccessUtils.uniqueResult(query);方法

  / **  
    * 查询单个对象  
    * @param id  
    * @return  
    */  
  public User findUserById(Integer id) {  
    String sql = "select * from tuser where id = ?";  
    List query = jdbcTemplate.query(sql, new BeanPropertyRowMapper(User.class), id);  
    return DataAccessUtils.uniqueResult(query);  

queryForMap使用如下方法:

public Map findUserMap(Integer id) {  
      String sql = "select * from tuser where id = ?";  
      Object[] args = new Object[]{id};  
      List> results =       
          jdbcTemplate.query(sql, args,  new RowMapperResultSetExtractor>(new ColumnMapRowMapper(), 1));      
          return DataAccessUtils.uniqueResult(results);      
        }  

文章原地址:http://shareisattitude.iteye.com/blog/2242963

转载记录,若有侵权妄告知,及时删除!

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