gpt4 book ai didi

java - MyBatis 是如何处理空结果集的?

转载 作者:IT老高 更新时间:2023-10-29 00:15:10 25 4
gpt4 key购买 nike

最近在使用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。我该怎么做?

最佳答案

作为查询的结果,最好有一个空集合而不是 null。在处理集合时,您通常会循环遍历每个项目并对它做一些事情,就像这样:

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

如果列表为空,它什么都不做。

但是,如果您返回 null,则必须保护您的代码免受 NullPointerException 的影响,并改为编写如下代码:

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 的调用,则可以进一步限制拦截器的范围。

关于java - MyBatis 是如何处理空结果集的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12156562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com