Mapper.xml中的foreach

对于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值

 

  • 16
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值