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>