mybatis foreach的使用

  foreach標籤在批量插入數據庫時很是方便,可是很容易出錯,我沒有注意括號的位置讓我折騰了一個半小時找問題,醉醉噠,因此在這裏記錄一下foreach的使用。數據庫

首先,這是insert批量插入正確的代碼:spa

<insert id="insertList" parameterType="map" useGeneratedKeys="true" keyProperty="messageId" >
       insert into message_table (
            message_id
            to_member_id,
            message_title,
            message_body,
            message_time,
            message_update_time,
            message_state,
            message_type,
            read_member_id,
            del_member_id,
            to_member_name,
            create_time,
            type_sn,
            type
            
       )values 
       <foreach collection="messageLt" item="m"  separator="," >
           (#{m.messageId},
         #{m.toMemberId},
         #{m.messageTitle},
         #{m.messageBody},
         UNIX_TIMESTAMP(NOW()),
         #{m.messageUpdateTime},
         #{m.messageState},
         #{m.messageType},
         #{m.readMemberId},
         #{m.delMemberId},
         #{m.toMemberName},
          UNIX_TIMESTAMP(NOW()),
         #{m.typeSn},
         #{m.type})
         </foreach>
       
</insert>

 我犯的錯誤是:code

  insert tableName(
    )values(
       <foreach collection="messageLt" item="m"  separator="," open="(" close=")" >
       </foreach>   
    )

產生的SQL結果是:insert tableName(a,b,c)values((?,?,?),(?,?,?),(?,?,?)) blog

報錯緣由插入行數不對應,正常結果應該是  insert tableName(a,b,c)values(?,?,?),(?,?,?),(?,?,?)。比較能夠很明顯看出問題。it

 下面是select的foreach使用:io

<select id="selectBatchMCoupon" parameterType="map" resultMap="memberCouponResultMap">
        select
            mc.mcoupon_id,
            mc.member_id,
            mc.coupon_id,
            mc.mcoupon_create_time,
            mc.class_show,
            c.coupon_title
            from 
            member_coupon mc
        left join eland_coupon c on c.coupon_id=mc.coupon_id 
        where 1=1 and mc.class_show=0 and 
        <if test="couponLt != null and couponLt != ''">
            mc.coupon_id in
            <foreach collection="couponLt" item="coupon" open="(" close=")" separator=",">
                #{coupon}
            </foreach>
                
        </if>
    </select>

 我犯的錯誤是:table

 <if test="couponLt != null and couponLt != ''">
            <foreach collection="couponLt" item="coupon" open="(" close=")" separator=",">
               mc.coupon_id =  #{coupon}
            </foreach>
      
        </if>

這個錯誤犯的我都尷尬。。。class

相關文章
相關標籤/搜索