आपकी क्वेरी के परिणामस्वरूप शून्य के बजाय खाली संग्रह होना बेहतर है। जब एक संग्रह आप आमतौर पर पाश प्रत्येक आइटम के माध्यम से काम करने के साथ और इसके साथ कुछ, कुछ इस तरह करते हैं:
List<User> resultList = (List<User>) sqlSession.select("statementId");
for (User u : resultList) {
//...
}
कुछ नहीं करता जो यदि सूची खाली है।
लेकिन अगर आप अशक्त लौटने के लिए, आप NullPointerExceptions के खिलाफ अपने कोड की रक्षा और इसके बजाय इस तरह कोड लिखने के लिए है:
List<User> resultList = (List<User>) sqlSession.select("statementId");
if (resultList != null) {
for (User u : resultList) {
//...
}
}
पहले दृष्टिकोण आमतौर पर बेहतर है और MyBatis ऐसे ही यह होता है, लेकिन आप इसे मजबूर कर सकता है शून्य वापस करने के लिए, अगर वह वास्तव में आप चाहते हैं।
इसके लिए आप एक MyBatis plugin लिख सकते हैं और किसी भी क्वेरी पर कॉल को रोक सकते हैं और फिर क्वेरी परिणाम खाली होने पर शून्य वापस आ सकते हैं।
आपके विन्यास ऐड में:
यहाँ कुछ कोड है
<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) {
}
}
फिर आप आगे गुंजाइश इंटरसेप्टर की अगर आप कॉल अवरोधन सीमित हो सकती है के बजाय ResultSetHandler
पर।