对于foreach标签的解释参考了网上的资料,具体如下:
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
foreach元素的属性主要有 item,index,collection,open,separator,close。
item :表示集合中每一个元素进行迭代时的别名
index :指定一个名字,用于表示在迭代过程中,每次迭代到的位置
open :表示该语句以什么开始
separator :表示在每次进行迭代之间以什么符号作为分隔符
close :表示以什么结束
在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
1.如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2.如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3.如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map
参考代码:
1、List<String>
参数为某对象时,collection="对象中变量名"
<select id="selectByParam" parameterType="com.xxx.StudentLearnedParam" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student_learned
where 1=1
<if test="curId != null">
AND curId = #{curId,jdbcType=CHAR}
</if>
<if test="curIds !=null and curIds.size()>0">
and curId in
<foreach collection="curIds" open="(" close=")" separator="," index="index" item="item">
#{item, jdbcType=VARCHAR}
</foreach>
</if>
</select>
参数为list类型时,collection="list"
<insert id="insertQuestions" parameterType="java.util.List">
insert into student_questions(mkId,queId)
values
<foreach collection="list" item="item" index="index" separator=",">
(#{item.mkId,jdbcType=VARCHAR},#{item.queId,jdbcType=VARCHAR})
</foreach>
</insert>
2、Integer[]
<select id="selectxxxByParam" resultType="com.xxx.CityCodeAndSum" parameterType="com.xxx.LessonDetailStatisticsParam">
select cityCode
from tb_xxx_statistics
where 1=1 and deleted = 0 and feedbackChannel = 3
<if test="jobTypes != null and jobTypes.length != 0">
AND job_type IN
<foreach close=")" collection="jobTypes" index="index" item="item" open="(" separator=" , ">
#{item,jdbcType=VARCHAR}
</foreach>
</if>
group by cityCode
</select>
3、Map<String,List<String>>
<select id="selectByStudentLessonIds" parameterType="java.util.Map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student_lesson_answers
where 1=1
<if test="studentLessonIds != null">
and studentLessonId in
<foreach collection="studentLessonIds" separator="," index="index" item="item" close=")" open="(">
#{item,jdbcType=VARCHAR}
</foreach>
</if>
</select>
注:studentLessonIds 为key值