쿼리 결과로 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
으로 변경하십시오.