浅说java的xml中的foreach用法

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>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值