Mybatis中and和循环or混用 (or转换成in)

本文介绍了在Mybatis中遇到and和多个or条件混合使用的问题,特别是当or条件涉及数组参数时。通过将or条件转为IN操作,并利用foreach循环,解决了在DAO层接口和Mybatis实现中的查询难题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这次项目用到一个and和or混用的场景 , 因为用到多个or(循环), 没想到好的办法

最终转换成用 IN实现:

场景:

用left join链接多个表, 多个条件and筛选, 其中状态(state)条件筛选出多个可选状态的条目,

本来想用and 和 or 但是 or的条件是个数组参数, 需要遍历states , 可能0个可能多个, 拼了半天没有成功 , 最后发现用 IN 和FOREACH就可以了

DAO层接口 :

List<OrderInfoForm> selectOrdersByStatesSelective(
            @Param(value="order")Order order,
            @Param(value="states")Integer[] states);

Mybatis实现:

<select id="selectOrdersByStatesSelective" resultMap="AllResultMap" >
    select 
    <include refid="All_Column_List" />
    from order_list
    LEFT JOIN product_method ON product_method.`code` = order_list.purchase_method
    LEFT JOIN product_color ON product_color.`code` = order_list.color
    LEFT JOIN product_guarantee ON product_guarantee.`code` = order_list.guarantee
    LEFT JOIN product_info ON order_list.product_id = product_info.id
    LEFT JOIN product_model ON product_info.model = product_model.`code`
    LEFT JOIN product_standard ON product_info.standard = product_standard.`code`
    LEFT JOIN product_state ON product_state.`code` = order_list.order_state
    LEFT JOIN product_apperance ON product_apperance.`code` = order_list.apperance
    LEFT JOIN product_brand ON product_brand.`code` = product_info.brand
    <where>
        <if test="order.orderNum != null " >
            order_num like "%"#{order.orderNum,jdbcType=VARCHAR}"%"
        </if>
        <if test="order.operator != null " >
            and operator like "%"#{order.operator,jdbcType=VARCHAR}"%"
        </if>
        <if test="order.purchaseTime != null" >
            and purchase_time = #{order.purchaseTime,jdbcType=DATE}
        </if>
        <if test="order.orderState != null" >
            and order_state = #{order.orderState,jdbcType=VARCHAR}
        </if>
        <if test="order.serialNum != null" >
            and serial_num like "%"#{order.serialNum,jdbcType=VARCHAR}"%"
        </if>
        
        <if test="states != null and states.length >0">
            <foreach collection="states" item="state" separator="," open=" and order_state in (" close=")">
                #{state,jdbcType=BIGINT}
            </foreach>
        </if>
    </where>
  </select>

这里的重点是:

 <if test="states != null and states.length >0">
            <foreach collection="states" item="state" separator="," open=" and order_state in (" close=")">
                #{state,jdbcType=BIGINT}
            </foreach>
</if>

把多个state的or关系转化为 states in (state1,state2,state3...)

in中用foreach循环

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值