MyBatis如何处理空结果集?

时间:2012-08-28 09:39:42

标签: java mysql mybatis

最近我使用的是Mybatis3,发现当你的SQL语句从数据库中获取一个空结果集时,Mybatis会创建一个新的List并将其返回给你的程序。

给出一些代码,例如:

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。 我怎么能这样做?

2 个答案:

答案 0 :(得分:20)

由于您的查询,最好有一个空集合而不是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) {
    }
}

如果拦截对ResultSetHandler而不是Executor的调用,则可以进一步限制拦截器的范围。

答案 1 :(得分:1)

由于以下原因,最好使用空列表而不是null。

不小心使用null会导致各种各样的错误。

此外,null是令人不快的模棱两可。很明显,null返回值应该是什么意思 - 例如,Map.get(key)可以返回null,因为map中的值为null,或者值不在map中。 Null可能意味着失败,可能意味着成功,可能意味着几乎任何事情。使用null以外的东西可以使你的意思清晰。

good discussion about null usage