spring2.5.5에서 JdbcTemplate사용시 org.springframework.dao.EmptyResultDataAccessException 발생
2008/11/26 19:14
spring에 JdbcTemplate를 사용하는 것이 편할거 같아서 이용을 하고 있다.
근데, ResultSet이 없으면 org.springframework.dao.EmptyResultDataAccessException이 발생을 한다.
대략 예외 메세지는 다음과 같다.
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
at org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:71)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:722)
at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:732)
at org.springframework.jdbc.core.simple.SimpleJdbcTemplate.queryForObject(SimpleJdbcTemplate.java:151)
at com.twc.ivr.dao.AccountProfileDaoImpl.findAccount(AccountProfileDaoImpl.java:107)
API를 살펴보니 별 내용이 없다.
http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/dao/EmptyResultDataAccessException.html
그래서 다음과 같이 해결을 했다.
try {
return (Blog)jdbcTemplate.queryForObject(sql, new Object[] { url }, mapper) ;
} catch (EmptyResultDataAccessException e) {
return null;
}
구글에서 검색을 해보면. 위와 같은 이유로 고생하는 사람들이 꽤 많다.
http://www.google.co.kr/search?complete=1&hl=ko&newwindow=1&q=JdbcTemplate++org.springframework.dao.EmptyResultDataAccessException&btnG=%EA%B2%80%EC%83%89&lr=&aq=f&oq=
http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/dao/IncorrectResultSizeDataAccessException
.html 예외는 http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/dao/EmptyResultDataAccessException.html를 서브클래스로 구현되었다.영회님이 API링크를 줘서 다시 잘 살펴보니 관련 내용이 있다.
queryForObject
public Object queryForObject(String sql, RowMapper rowMapper) throws DataAccessException
- Description copied from interface:
JdbcOperations- Execute a query given static SQL, mapping a single result row to a Java object via a RowMapper.
Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded
queryForObjectmethod withnullas argument array.- Specified by:
queryForObjectin interfaceJdbcOperations
- Parameters:
sql- SQL query to executerowMapper- object that will map one object per row- Returns:
- the single mapped object
- Throws:
IncorrectResultSizeDataAccessException- if the query does not return exactly one rowDataAccessException- if there is any problem executing the query- See Also:
JdbcOperations.queryForObject(String, Object[], RowMapper)
- Execute a query given static SQL, mapping a single result row to a Java object via a RowMapper.
권남님은 그래서 queryForList를 사용하라고 하는데, 내 생각은 하나의 row면 queryForObject를 사용하고 예외처리로 널을 리턴하는 것이 더 좋아보인다. collection이 아닌 데이터를 1개 리턴을 할때 예외가 난다고 리스트로 collection으로 가져온다는 것은 좀 이상하다. 코드에서 의도를 볼때 queryForObject vs queryForList를 사용하는 것은 의미적 차이가 크다.
http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html
