Mybatis中的foreach用法
元素属性
- item: 集合中元素迭代时的别名,该参数为必选。
- index:在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选
- open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选
- separator:元素之间的分隔符。","形式
- close :foreach代码的关闭符号,一般是")“和open=”("合用。常用在in(),values()时。该参数可选。
- collection:三种情况
- 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 如果使用Map封装了,collection的属性值为对应的Key
List对象集合查询
Controller层方法内参数传入List对象集合,Mybatis内foreach方法
<select id="selectTestList" parameterType="com.bxy.leaveapply.domain.Test" resultMap="LeaveResult">
SELECT * FROM `test` a
where 1=1
<if test="TestList !=null">
<foreach collection="list" item="item" index="index" open="and (" separator="or" close=")">
a.user_id = #{item.userId} and a.leave_status = #{item.leaveStatus}
and #{item.startTime} between a.start_time and a.end_time
</foreach>
</if>
</select>
根据数组中的Id删除
<delete id="deleteTestByIds" parameterType="String">
delete from test where test_id in
<foreach item="testId" collection="array" open="(" separator="," close=")">
#{testId}
</foreach>
update修改
第一种:
Dao层的数据为:
int updateForEachByYiKuId(@Param("list") List<WmsMoveDetail> list,@Param("scanningFlag") Byte scanningFlag,@Param("remark") String remark);
Mapper中的sql语句:
<update id="updateForEachByYiKuId" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update wmsmovedetail
<set >
<if test="scanningFlag != null and scanningFlag !=''" >
ScanningFlag = #{scanningFlag},
</if>
<if test="remark != null and remark !=''" >
Remark = #{remark},
</if>
</set>
where YiKuId = #{item.yiKuId} and RowNo = #{item.rowNo}
</foreach>
</update>
在使用foreach处理update时,后台输出sql一直报错,但是确定没问题。查看jdbc的设置,缺少**&allowMultiQueries=true**
MySQL连接数据库时,添加语句:“allowMultiQueries=true”的作用:
1.可以在sql语句后携带分号,实现多语句执行。
2.可以执行批处理,同时发出多个SQL语句。
第二种:
Dao层的数据为:
int updateListByChuKuIdAndRowNo(@Param("list") List<WmsOutputDetail> list);
Mapper中的sql语句
<update id="updateListByChuKuIdAndRowNo" parameterType="java.util.List">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update wmsoutputdetail
<trim prefix="SET" suffixOverrides=",">
<if test="item.remark != null and item.remark != ''">
Remark = #{item.remark},
</if>
<if test="item.scanningFlag != null and item.scanningFlag != ''">
ScanningFlag = #{item.scanningFlag},
</if>
</trim>
where ChuKuId = #{item.chuKuId} and RowNo = #{item.rowNo}
</foreach>
</update>