2012-08-28 2 views
9

최근에 Mybatis3을 사용하고 있는데 SQL 문에서 데이터베이스에서 빈 결과 집합을 가져 오면 Mybatis는 새 List을 만들고이를 프로그램에 반환합니다. MyBatis는 빈 결과 집합을 어떻게 처리합니까?

이 같은 일부 코드를 감안할 때 :
List<User> resultList = (List<User>)sqlSession.select("statementId"); 

<select id="statementId" resultType="User"> 
    select * from user where id > 100 
</select> 

위의 SQL은 더 행을 반환 없다고 가정 (즉, 100 이하 ID 더있다).

변수 resultList은 비어있는 List이되지만 대신 null이되고 싶습니다. 어떻게하면됩니까?

답변

15

쿼리 결과로 null 대신 빈 컬렉션을 갖는 것이 좋습니다. 각 항목을 통해 수집하면 일반적으로 루프 작업과 같은 그 뭔가, 뭔가를 할 때 : 목록이 비어있는 경우

List<User> resultList = (List<User>) sqlSession.select("statementId"); 
for (User u : resultList) { 
    //... 
} 

아무것도하지 않는다. 당신이 null을 반환하는 경우

는, 당신은 NullPointerExceptions를으로부터 코드를 보호하고 대신 다음과 같은 코드를 작성해야 :

List<User> resultList = (List<User>) sqlSession.select("statementId"); 
if (resultList != null) { 
    for (User u : resultList) { 
    //... 
    } 
} 

첫 번째 방법은 일반적으로 더 나은와의 MyBatis는 그런 식으로 그것을 않습니다,하지만 당신은 그것을 강제 할 수 그것이 정말로 당신이 원하는 것이면, null을 돌려주는 것.

이 경우 MyBatis plugin을 작성하고 모든 쿼리에 대한 호출을 가로 채고 쿼리 결과가 비어 있으면 null을 반환 할 수 있습니다. 구성 추가에

: 여기

몇 가지 코드

<plugins> 
    <plugin interceptor="pack.test.MyInterceptor" /> 
</plugins> 

인터셉터 코드 : 당신이 전화를 차단하는 경우 다음 더 인터셉터의 범위를 제한 할 수

package pack.test; 

import java.util.List; 
import java.util.Properties; 

import org.apache.ibatis.executor.Executor; 
import org.apache.ibatis.mapping.MappedStatement; 
import org.apache.ibatis.plugin.Interceptor; 
import org.apache.ibatis.plugin.Intercepts; 
import org.apache.ibatis.plugin.Invocation; 
import org.apache.ibatis.plugin.Plugin; 
import org.apache.ibatis.plugin.Signature; 
import org.apache.ibatis.session.ResultHandler; 
import org.apache.ibatis.session.RowBounds; 

@Intercepts({ @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) 
public class MyInterceptor implements Interceptor { 
    public Object intercept(Invocation invocation) throws Throwable { 
     Object result = invocation.proceed(); 
     List<?> list = (List<?>) result; 
     return (list.size() == 0 ? null : result); 
    } 

    public Object plugin(Object target) { 
     return Plugin.wrap(target, this); 
    } 

    public void setProperties(Properties properties) { 
    } 
} 

Executor 대신 ResultSetHandler으로 변경하십시오.

1

다음 이유 때문에 항상 null 대신 빈 목록을 사용하는 것이 좋습니다.

null을 부주의하게 사용하면 다양한 버그가 발생할 수 있습니다.

또한 null은 불명확합니다. null 반환 값이 의미하는 바는 거의 없습니다. 예를 들어 Map.get (key)는지도의 값이 null이거나 값이지도에 없기 때문에 null을 반환 할 수 있습니다. Null은 실패를 의미 할 수 있고, 성공을 의미 할 수 있으며, 거의 모든 것을 의미 할 수 있습니다. null이 아닌 다른 것을 사용하면 의미가 명확 해집니다.

good discussion about null usage

관련 문제