回顾一个旧项目,并发现此Spring JDBC代码段:
public User getUser(String username) {
String sql = "SELECT * FROM USER WHERE username = ?";
return getJdbcTemplate().queryForObject(
sql,
new Object[] { username },
new RowMapper<UserAttempts>() {
public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setAge(rs.getInt("age"));
user.setLastModified(rs.getDate("lastModified"));
return user;
}
});
}
问题
开发人员假定找不到记录时将返回null。
User user = abc.getUser("mkyong");
if(user == null){
//...do something
}
问题是,Spring抛出EmptyResultDataAccessException
,而不是在找不到记录时返回null。
JdbcTemplate .java
package org.springframework.jdbc.core;
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
//...
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);
}
DataAccessUtils.java
package org.springframework.dao.support;
public abstract class DataAccessUtils {
//...
public static <T> T requiredSingleResult(Collection<T> 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();
}
PS Spring 3.2.8.RELEASE版本
解
返回null是非常标准的,想知道Spring为什么要抛出EmptyResultDataAccessException
吗? 要解决此问题,只需捕获异常并返回null。
public User getUser(String username) {
String sql = "SELECT * FROM USER WHERE username = ?";
try {
User user = getJdbcTemplate().queryForObject(
sql,
new Object[] { username },
new RowMapper<UserAttempts>() {
public UserAttempts mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setAge(rs.getInt("age"));
user.setLastModified(rs.getDate("lastModified"));
return user;
}
});
return user;
} catch (EmptyResultDataAccessException e) {
return null;
}
}
标签: Spring JDBC