【问题标题】:MyBatis - Convert query-check from a single object to check on a collectionMyBatis - 将查询检查从单个对象转换为检查集合
【发布时间】:2026-01-30 04:40:01
【问题描述】:

有以下代码。

选择一堆列来自where ... 左连接 ...where

<if test="taskowner != null">
    AND (o.primary_taskowner_id = #{taskowner.id}
         OR o.secondary_taskowner_id = #{taskowner.id})
</if>

在这种情况下,taskowner 是我的 combobox 中的单个选定对象。

要求已经改变,现在我需要组合框-多选。如何将查询的那部分调整为组合框多选(我想在集合中的每个对象上运行相同的条件)?

我想出了这个:

<if test="taskowners != null and taskowners.empty == false">

     AND o.primary_taskowner_id 
    <foreach item="taskowner" collection="taskowners" open="(" separator="," close=")">
         #{taskowner.id}
   </foreach>

    OR o.secondary_taskowner_id 
    <foreach item="taskowner" collection="taskowners" open="(" separator="," close=")">
         #{taskowner.id}
    </foreach>
</if> 

但结果不是我所期望的。我尝试了该解决方案的多种变体,但都没有奏效。并没有在网上找到任何有用的东西。

提前致谢。

【问题讨论】:

  • 解释所需的逻辑,也许用示例 SQL。你想要x in (a, b, c) or y in (q, r, s)这样的东西吗?这似乎是你写的。
  • 第 1 步是创建一个 SQL DML,它可以满足您的需求(用于 3 个或元素)。
  • @DwB 我有一组任务所有者;每个任务所有者都有 some_id。我想加入 some_id = primary_taskowner_id 的行,如果没有找到该 primary_taskowner_id 则检查 some_id = secondary_taskowner_id 的位置。我想对每个集合条目执行检查。
  • 没错,为此编写 SQL,MyBatis 的实现将变得直截了当。

标签: java mybatis


【解决方案1】:

您想要的 SQL 似乎是这个的变体:

... and
(o.prim_id = '7' or o.second_id = '7') or
(o.prim_id = '8' or o.second_id = '8') or
(o.prim_id = '9' or o.second_id = '9') ...

使用一个 foreach 循环来生成它。 MyBatis 的“代码”会是这样的:

AND
(
<foreach ...blah>
   (o.prim_id = {tid} or o.second_id = {tid})
   <conditional or> (I'm sure mybatis provides this, but I dont remember the syntax.
</foreach>
)

【讨论】:

    【解决方案2】:

    我找到了解决方案。感谢DwB 向我展示了正确的方向。

    <if test="taskowners != null and taskowners.empty == false">
    
        AND (o.primary_taskowner_id IN
        <foreach item="taskowner" collection="taskowners" open="(" separator="," close=")">
            #{taskowner.id}
        </foreach>
    
        OR o.secondary_taskowner_id IN
        <foreach item="taskowner" collection="taskowners" open="(" separator="," close=")">
            #{taskowner.id}
        </foreach>)
    </if>
    

    【讨论】: