MyBatis如何处理空结果集?

use*_*796 12 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>
Run Code Online (Sandbox Code Playgroud)

假设上面的SQL没有返回任何行(即没有大于100的id).

变量resultList将是空的List,但我希望它是null相反的.我怎样才能做到这一点?

Bog*_*dan 22

由于您的查询,最好有一个空集合而不是null.使用集合时,您通常会遍历每个项目并使用它执行某些操作,如下所示:

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

如果列表为空,则不执行任何操作.

但是如果你返回null,你必须保护你的代码免受NullPointerExceptions的影响,并编写这样的代码:

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

第一种方法通常更好,MyBatis就是这样做的,但你可以强制它返回null,如果这真的是你想要的.

为此,您可以编写MyBatis 插件并拦截对任何查询的调用,如果查询结果为空,则返回null.

这是一些代码:

在您的配置中添加:

<plugins>
   <plugin interceptor="pack.test.MyInterceptor" />
</plugins>
Run Code Online (Sandbox Code Playgroud)

拦截器代码:

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) {
    }
}
Run Code Online (Sandbox Code Playgroud)

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