spring JdbcTemplate的queryForObject為空返回異常情況的一個處理
Posted on 2011-10-25 10:59 瘋狂 閱讀(15573) 評論(1) 編輯 收藏 所屬分類: spring 、讀代碼看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的通用的方法:
/**
* 可以用于處理查詢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);
}
});
}
具體的工程可以在http://www.aygfsteel.com/freeman1984/archive/2011/10/24/361899.html里面下載。
先看下spring的這段源碼:















下面是我的一個方法,其他的方法請大家補充:
寫一個接口定義規則:




















最后是調用實例(根據id查用戶):







具體的工程可以在http://www.aygfsteel.com/freeman1984/archive/2011/10/24/361899.html里面下載。