MyBatis单对象查询校验转集合查询校验方案咨询
Solution for MyBatis Multi-Select Task Owner Query
Got it, let's adjust this query to support multiple selected task owners. Here's a straightforward, clean way to modify your MyBatis snippet:
Step 1: Update Your Input Parameter Type
First, make sure your mapper method accepts a collection (like List<TaskOwner> or Set<TaskOwner>) instead of a single TaskOwner object. Keep using a clear parameter name (e.g., taskowner as you did before—just now it’s a collection instead of a single instance).
Step 2: Use <foreach> to Generate Conditions for Each Selected Owner
Replace your original <if> block with a combination of a non-empty check and a <foreach> loop to build the multi-owner matching logic:
<if test="taskowner != null and taskowner.size() > 0"> AND ( <foreach collection="taskowner" item="owner" separator=" OR "> (o.primary_taskowner_id = #{owner.id} OR o.secondary_taskowner_id = #{owner.id}) </foreach> ) </if>
What This Does:
- The outer
<if>check ensures we only add this condition block when there are selected owners—prevents invalid SQL from empty collections. - The
<foreach>tag loops through each selected task owner:collection="taskowner": Targets your collection parameter name. If you used@Param("taskOwners")in your mapper method, use that name instead.item="owner": Assigns an alias to each element in the collection, so we can reference its ID with#{owner.id}.separator=" OR ": Adds anORbetween each owner’s condition group, so any match (primary or secondary) for any selected owner will qualify the row.
- The outer parentheses wrap all owner conditions together to maintain proper logic precedence with other parts of your WHERE clause.
Quick Tips:
- If your parameter is an array instead of a collection, set
collection="array"in the<foreach>tag. - Always validate the collection is non-empty before using it to avoid SQL syntax errors.
内容的提问来源于stack exchange,提问作者t_sologub
相关产品推荐
相关产品推荐

