select * from users where id in ()
查询如上所示。
<select id="getByIds" resultMap="BaseResultMap">
SELECT
<include refid="BaseColumnList"/>
FROM users
WHERE id IN
<foreach item="id" collection="ids"
open="(" separator="," close=")">
#{id}
</foreach>
</select>
如果参数ids
为空,则Mybatis将抛出BadSqlGrammarException,这将生成类似“ select * from users where id in
”的查询。
如果ids
为空,如何跳过查询并返回空列表?
如果id为空,如何跳过查询并返回空列表?
要跳过查询(不执行查询),只需不调用Mybatis。调用代码应检查id是否为空:
return null == ids || ids.isEmpty() ? new ArrayList<User>() : session.select("getByIds", ids);
这正是问题中要问的。
如果您确实希望Mybatis处理此问题,则生成的查询必须有效,因为必须执行(然后不跳过)以快速返回空结果。这意味着忘记类似的东西,id = <!-- a value that will never exist in the table -->
因为它肯定会涉及(免费和无用的)全面扫描来搜索不存在的值。然后:
WHERE
<choose>
<when test="ids==null || ids.isEmpty()">
1 = 0 <!-- a test returning false, to adapt depending on you DB vendor -->
</when>
<otherwise>
id IN <foreach item="id" collection="ids" open="(" separator="," close=")">#{id}</foreach>
</otherwise>
</choose>
确认的另一种选择是使用拦截器在执行查询之前“取消”查询,但是对于必须在此处实现的操作,这肯定是过分复杂的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句