foreach标签在批量插入数据库时非常方便,但是很容易出错,我没有注意括号的位置让我折腾了一个半小时找问题,醉醉哒,所以在这里记录一下foreach的使用。
首先,这是insert批量插入正确的代码:
<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>
我犯的错误是:
insert tableName( )values( <foreach collection="messageLt" item="m" separator="," open="(" close=")" > </foreach> )
产生的SQL结果是:insert tableName(a,b,c)values((?,?,?),(?,?,?),(?,?,?))
报错原因插入行数不对应,正常结果应该是 insert tableName(a,b,c)values(?,?,?),(?,?,?),(?,?,?)。比较可以很明显看出问题。
下面是select的foreach使用:
<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>
我犯的错误是:
<if test="couponLt != null and couponLt != ‘‘"> <foreach collection="couponLt" item="coupon" open="(" close=")" separator=","> mc.coupon_id = #{coupon} </foreach> </if>
这个错误犯的我都尴尬。。。
时间: 2024-10-14 02:36:04