spring JdbcTemplate的queryForObject为空返回异常情况的一个处理
看spring的queryForObject(如果查询结果条数为0或者大于1)都会返回异常,我们希望没查到返回null,这样我们就可以给用户提示没有找到,要不我们的每个queryforObject,queryForInt...等等方法都需要手动拦截这个异常来判断为空,才能做出判断。
先看下spring的这段源码:
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();
?}
下面是我的一个方法,其他的方法请大家补充:
写一个接口定义规则:
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查用户):
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);
????????????}
????????});
????} 1 楼 zhuxinyu 2011-10-26 文章编排有点乱。