ibatis를 사용할 때, 간혹 DB에 원하는 데이터가 없으면 어떡하지?라는 생각이 들 때가 있다.
대부분의 경우 문제가 없겠지만, 다른 사람의 코드를 보다가 궁금함에 검색했다.
먼저 queryForObject()를 사용하는 경우 null을 리턴한다.
그냥 단순하게 생각을 해도, 데이터가 없는 경우 어떤 Object를 리턴해야 하는지 애매하다.
실제로 코드를 보면, result row가 많은 경우 exception, 1개인 경우는 리턴, 없으면 null을 리턴한다.
MappedStatement.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public Object executeQueryForObject(StatementScope statementScope, Transaction trans, Object parameterObject, Object resultObject) throws SQLException { try { Object object = null; DefaultRowHandler rowHandler = new DefaultRowHandler(); executeQueryWithCallback(statementScope, trans.getConnection(), parameterObject, resultObject, rowHandler, SqlExecutor.NO_SKIPPED_RESULTS, SqlExecutor.NO_MAXIMUM_RESULTS); List list = rowHandler.getList(); if (list.size() > 1) { throw new SQLException( "Error: executeQueryForObject returned too many results."); } else if (list.size() > 0) { object = list.get(0); } return object; } catch (TransactionException e) { throw new NestedSQLException( "Error getting Connection from Transaction. Cause: " + e, e); } } |
하지만 queryForList()를 사용하는 경우 empty list가 리턴된다.
리스트의 경우에는 명확하게 List이기 때문일까?
결국 DefaultRowHandler의 값을 리턴하는데 이 객체의 초기값이 new ArrayList()이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public List executeQueryForList(StatementScope statementScope, Transaction trans, Object parameterObject, int skipResults, int maxResults) throws SQLException { try { DefaultRowHandler rowHandler = new DefaultRowHandler(); executeQueryWithCallback(statementScope, trans.getConnection(), parameterObject, null, rowHandler, skipResults, maxResults); return rowHandler.getList(); } catch (TransactionException e) { throw new NestedSQLException( "Error getting Connection from Transaction. Cause: " + e, e); } } |
DefaultRowHandler.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class DefaultRowHandler implements RowHandler { private List list = new ArrayList(); public void handleRow(Object valueObject) { list.add(valueObject); } public List getList() { return list; } public void setList(List list) { this.list = list; } } |
여튼 queryForList()를 사용하는 경우, (result != null) 방식으로 체크를 하면 오류가 발생할 것이다.
나같은 경우에 그동안 문제가 없었던 것은 CollectionUtils.isNotEmpty()를 사용했기 때문이다.
이래서 코딩도 평소 습관이 중요하다는 생각이 든다.
참고 : http://blog.naver.com/PostView.nhn?blogId=tykim00&logNo=90086378689
덧붙임 :
http://ibatis.apache.org 를 보면 ibatis가 apache project에서 빠졌다.
mybatis라는 이름으로 google code에서 계속 진행중이란다.
2010년에 옮겼다는데 아직도 모르고 있었다니…ㅠ.ㅠ