spring JdbcTemplate的queryForObject为空返回异常情况的一个处理

看spring的queryForObject(如果查询结果条数为0或者大于1)都会返回异常,我们希望没查到返回null,这样我们就可以给用户提示没有找到,要不我们的每个queryforObject,queryForInt...等等方法都需要手动拦截这个异常来判断为空,才能做出判断。
先看下spring的这段源码:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> public   < T >  T queryForObject(String sql, Object[] args, RowMapper < T >  rowMapper)  throws  DataAccessException  {
  List
<T> results = query(sql, args, new RowMapperResultSetExtractor<T>(rowMapper, 1));
  
return DataAccessUtils.requiredSingleResult(results);
}

public   static   < T >  T requiredSingleResult(Collection < T >  results)  throws  IncorrectResultSizeDataAccessException  {
  
int size = (results != null ? results.size() : 0);
  
if (size == 0{//记录为o返回异常
   throw new EmptyResultDataAccessException(1);//此异常继承自IncorrectResultSizeDataAccessException
  }

  
if (results.size() > 1{有多条记录返回异常
   
throw new IncorrectResultSizeDataAccessException(1, size);
  }

  
return results.iterator().next();
 }



下面是我的一个方法,其他的方法请大家补充:
写一个接口定义规则:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> public   interface  JdbcTemplateCallBack < T >   {
    
public  T querys(JdbcTemplate jdbcTemplate);
}

然后是BaseDao的通用的方法:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> /** */ /**
     * 可以用于处理查询queryfor 为空或者多条的时候返回异常的情况,现在返回null,主要是拦截IncorrectResultSizeDataAccessException异常,以及子类
     * 
@param jdbcTemplateCallBack
     * 
@return
     * 
@throws DaoException
     
*/

    
public   < T >  T queryNullAble(JdbcTemplateCallBack < T >  jdbcTemplateCallBack)  throws  DaoException  {
        
try {
            
return jdbcTemplateCallBack.querys(getJdbcTemplate());
        }
 catch (Exception e) {
                
if((e instanceof IncorrectResultSizeDataAccessException)
                        
&&((IncorrectResultSizeDataAccessException)e).getActualSize()==0)
                    
return null;
            
//其他的异常正常抛出
            throw new DaoException(e);
        }

    }


最后是调用实例(根据id查用户):

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> public  SUser getUserByColunm( final  String columnName,  final  Object value)  throws  DaoException  {
        
return queryNullAble(new JdbcTemplateCallBack<SUser>() {
            
public SUser querys(JdbcTemplate jdbcTemplate) {
                
return jdbcTemplate.queryForObject("select *  from suser where "+columnName+"=?"new BeanPropertyRowMapper(SUser.class),value);
            }

        }
);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值