Mybatis中的foreach用法
目录
- Mybatis中的foreach用法
-
- 元素属性
-
- List对象集合查询
- 根据数组中的Id删除
- 待完善补充。。。
元素属性
- 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>