浅说java的xml中的foreach用法

文章详细介绍了XML中foreach元素在处理集合数据时的应用,包括collection属性的不同情况,如list、array以及多个参数时的处理。还举例展示了如何根据参数类型设置collection属性,并在SQL查询和插入语句中使用foreach。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

XML中的foreach

foreach元素的属性主要有 collection,item,index,separator,open,close。

collection:表示集合,数据源
在使用foreach的时候最关键的也是最容易出错的就是collection属性,
该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,
主要有一下3种情况:

如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了
item :表示集合中的每一个元素

index :用于表示在迭代过程中,每次迭代到的位置

separator :表示在迭代时数据以什么符号作为分隔符

open :表示该语句以什么开始

close :表示以什么结束

一、当mapper中参数是单个且是数组的时候

List<String>  findName(String[] ids);

xml中的collection是array:

 select name from tb1  where  id in
        <foreach collection="array" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>

二、当mapper中的参数是单个且是集合的时候

List<String>  findName(List ids);

xml中的collection是list:

 select name from tb1  where  id in
        <foreach collection="list" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>

三、当mapper中的参数是多个,都需要绑定@Param注解,此时xml中collection的值是绑定注解的参数(无论参数是数组还是集合)

List<String>  findName(@Param("ids")List names,@Param("age") String data);List<String>  findName(@Param("ids")String[] names,@Param("age") String data);

xml中的collection是都是ids:

 select name from tb1  where  id in
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>

四、当mapper中参数是对象,对象中包含参数集合或数组ids的时候
mapper:

List<String>  findName(@Param("dto) Student student);

xml:

 select name from tb1  where  id in
        <foreach collection="dto.ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>

五、当sql是插入语句的时候
mapper:

int addStudent(List<Student > students);
insert into Student(name,age)
values
 <foreach collection="list" item="entity" separator=",">
               (#{entity.name}, #{entity.age}</foreach>

六、模糊查询

 select name from tb1  where  is_delete = 0 
           <if test="dto.nameList!= null and dto.nameList.size() > 0">
           and
        <foreach collection="dto.ids" item="id" open="(" separator="or" close=")">
           name  like concat('%',#{item},'%')
        </foreach>
        />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值