foreach遍历迭代的常见用法

foreach遍历迭代的常见用法

代码示例:

SELECT
      honor
    FROM
      member_manager_table m
    LEFT JOIN sys_user_table u
    ON
      m.member_id = u.user_id
    WHERE
      u.user_id IN
   <foreach  item="item"  collection="list"  index="index"  open="(" separator="," close=")">
        #{item}
    </foreach>

dao层的写法:int queryMemberTotalHonor(List list);
foreach 也就是遍历迭代,在SQL中通常用在 in 这个关键词的后面
foreach元素的属性主要有 item,index,collection,open,separator,close。
分别代表:
item:表示集合中每一个元素进行迭代时的别名,
index:用于表示在迭代过程中,每次迭代到的位置,
open:表示该语句以什么开始,
separator:表示在每次进行迭代之间以什么符号作为分隔 符,
close:表示以什么结束

而最为重要的就是collection属性了,既然是迭代就表示传入的参数是多个,这时候传入的参数就有以下几种可能:

1. 传入的参数为list的时候

对应的Dao中的Mapper文件是:

public List selectByIds(List ids);

xml文件代码片段:

<select id="selectByIds" resultType="com.txw.pojo.User">
        select * from user where id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
</select>

2. 传入的参数为Array的时候
对应的Dao中的Mapper文件是:
public List selectByIds(int[] ids);
xml文件代码片段:

<select id="selectByIds" resultType="com.txw.pojo.User">
        select * from user where id in
        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

3. 传入的参数为Map的时候
对应的Dao中的Mapper文件是:
public List selectByIds(Map<String, Object> params);
xml文件代码片段:

<select id="selectByIds" resultType="com.txw.pojo.User">
        select * from user where  id in
        <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

map的时候需要注意的是:collection的值“ids”是存储在map中的key(比如:map.put(“ids”,ids));尤其需要注意;

批量插入实例:
mapper接口:

void batchInsert(@Param("idsAppConfigSmsScenes")List<idsAppConfigSmsSceneDTO> idsAppConfigSmsScenes);

xml写法

<insert id="batchInsert">
	insert into `ids_app_config_sms_scene`(`id`,`instance_id`,`sms_config_id`,`scene_type`,`scene_name`,`scene_code`,`sms_type`,`scene_template_code`,`scene_template_content`,`created_date`,`created_by`,`updated_date`,`updated_by`) values
	<foreach collection="idsAppConfigSmsScenes" item="item" separator=",">
	(
		#{item.id},
		#{item.instanceId},
		#{item.smsConfigId},
		#{item.sceneType},
		#{item.sceneName},
		#{item.sceneCode},
		#{item.sceneTemplateCode},
		#{item.sceneTemplateContent},
		#{item.createdDate},
		#{item.createdBy},
		#{item.updatedDate},
		#{item.updatedBy}
	)
	</foreach>
</insert>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神雕大侠mu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值