Mybatis中foreach的使用详解

 更新时间:2024年11月20日 09:32:24   作者:星空寻流年  
Mybatis中foreach标签的使用详解,包括属性说明、代码示例和总结,感兴趣的朋友跟随小编一起看看吧

一、foreach 属性使用

<foreach collection="list" index="index" item="mchntCd" open="(" close=")" separator=",">
   #{mchntCd}
</foreach>
  • item:  集合中元素迭代时的别名,该参数为必选,通过别名进行取值
  • index:在list和数组中,index是元素的序号,在map中,index是元素的key,非必填
  • open: foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。非必填
  • separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。非必填
  • close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。非必填
  • collection: 要做foreach的对象,作为入参
    • 传入是集合,也就是接口里面用的  List<String> nameList    那么 使用 collection = “list”
    • 传入的是数组,接口里面 String[] namestrs ,那么 使用 collection = “array”
    • 如果传入的是一个实体bean,实体bean里面有一个属性为 list<String> ids 那么collection = “ids ”,如果实体bean中对应ids是一个对象,ids 里面有一个属性为 List<Stirng> usernames,那么collection = “ids.usernames”

二、代码使用         

1、实体类 list<String>  mchntCds

 mapper接口  ---》 list方式

int queryDiscDerateCount(List<String> mchntCds);

mapper映射xml:

<select id="queryDiscDerateCount"  resultType="Integer">
   select count(*) from t_mchnt_disc_config  where mchnt_cd in
   <foreach collection="list" index="index" item="mchntCd" open="(" close=")"  separator=",">
      #{mchntCd}
   </foreach>
</select>

2、实体类 list<User>  userlist,实体类中有 list 属性

实体类:

@Data
public class MchntDiscDerateDto {
   private String mchntCd = "";
}

mapper接口

List<TMchntDerateInfoDto> getDiscDerateList(List<MchntDiscDerateDto> discDto);

mapper映射xml:

<select id="getDiscDerateList" parameterType="MchntDiscDerateDto" resultType="TMchntDerateInfoDto">
   select
    t_mchnt_disc_derate_config
      where
         mchnt_cd in
         <foreach collection="list" index="index" item="user" open="(" close=")" separator=",">
            #{user.mchntCd}
         </foreach>
</select>

3、数组  String[] params     

用 array 

mapper 接口

int queryDiscDerateCount(String[] mchntCds);

mapper映射xml:

<select id="queryDiscDerateCount"  resultType="Integer">
   select count(*) from t_mchnt_disc_derate_config where mchnt_cd in
   <foreach collection="array" index="index" item="mchntCd" open="(" close=")" separator=",">
      #{mchntCd}
   </foreach>
</select>

4、传入的参数是实体类,并且实体中包含数组和集合

实体类:

@Data
public class UserVo {
    private Long id;
    private Long supplierId;
    private Long[] ids;
    private List<Long> clientIdList;
}

mapper接口

List<UserVo> queryList(UserVo select);

mapper映射文件xml

    <select id="queryList" resultType="UserVo" parameterType="UserVo">
        select *
        from bms_bills_memo
        <where>
        and id in
        <foreach collection="ids" open="(" close=")" item="id" separator=",">
            #{id}
        </foreach>
        and
        client_id in
        <foreach collection="clientIdList" separator="," item="detail" open="(" close=")" >
            #{detail}
        </foreach>
        </where>
    </select>

5、传入多个list或者array,不使用实体进行封装。用注解@Params, collection使用到Param中定义的别名

mapper接口

List<UserVo> queryList(@Param("idArray") Long[] array, @Param("clientIdList") List<Long> list);

mapper映射文件xml

    <select id="queryList" resultType="UserVo">
        select *
        from t_user_inf
        <where>
            and id in
            <foreach collection="idArray" open="(" close=")" item="id" separator=",">
                #{id}
            </foreach>
            and
            client_id in
            <foreach collection="clientIdList" separator="," item="detail" open="(" close=")" >
                #{detail}
            </foreach>
        </where>
    </select>

6、map参数

当我们传入的参数为 Map<String,Objject>的时候,那么能不能正常使用 foreach呢,答案是肯定的,因为对象也是类似于map结构啊

    /**
     *  map 获取数据
     * @param map
     * @return
     */
    List<SysUser> getUserByIds(Map<String,Object> map);
 
 
    // xml
    <select id="getUserByIds" resultMap="BaseResultMap">
    select
        <include refid="Base_Column_List" />
    from t_sys_user
    where status = #{status}
    and id in
    <foreach collection="ids" item="id" open="(" close=")" separator=",">
        #{id}
    </foreach>
  </select>

实际调用:

     @Test
    public void testMapUsers() {
        Map<String,Object> params = new HashMap<>();
        params.put("status", "1");
        params.put("ids", Arrays.asList(1,2,3,4,5,6,7,8));
        List<SysUser> all = sysUserDao.getUserByIds(params);
        try {
            System.out.println(new JsonMapper().writeValueAsString(all));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

调用结果:

三、总结

    1、mapper 接口中添加 @Param注解的场合,list,array将会失效;

    2、使用了 @Param注解 collection的内容需要使用Param中的别名来指定你需要用到的list或者array

扩展:Mybatis中foreach的使用

首先我们要明白的是foreach的本质就是把数据库能执行的sql在xml中按照一定语法来进行拼接,所以拼接之前,我们了解一下foreach标签中几个常见元素的作用
1.collection
‌List或Array‌:如果传入的参数类型是List或Array,collection属性的默认值分别是list和array。如果需要自定义集合名称。
‌Map‌:如果传入的参数是Map,collection属性可以指定遍历Map的keys、values或entrySet
2.item
集合遍历中每一个元素的别名
3.open
拼接sql时最前面拼接的字符串
4.separator
拼接sql时候两个元素之间的分隔字符串
5.close
拼接sql时最后面拼接的字符串
6.index
index‌:在List或Array中,index为元素的序号索引;在Map中,index为遍历元素的key值。
举一个简单的例子
一个简单的sql

select * from blog where title is not null and (id=1 or id=2 or id=3)

1.我们使用map集合作为参数实现拼接

<select id="queryBlogForeach" parameterType="map" resultType="blog"> select * from blog <where> title is not null <foreach collection="ids" item="id" open="and (" separator="or" close=")"> id=#{id} </foreach> </where> </select>

2.我们使用list集合作为参数实现拼接

<select id="queryBlogForeach2" parameterType="list" resultType="blog"> select * from blog <where> title is not null <foreach collection="list" item="id" open="and (" separator="or" close=")"> id=#{id} </foreach> </where> </select>

到此这篇关于Mybatis中foreach的使用的文章就介绍到这了,更多相关Mybatis foreach使用内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java向文件末尾添加内容示例分享

    java向文件末尾添加内容示例分享

    本文为大家提供一个java向文件末尾添加内容的示例分享,大家参考使用吧
    2014-01-01
  • MyBatisPlus 封装分页方法示例

    MyBatisPlus 封装分页方法示例

    本文主要介绍了基于MybatisPlus的分页插件封装,包括分页结果对象、查询对象的封装,以及对象转换处理,具有一定的参考价值,感兴趣的可以了解一下
    2024-12-12
  • Spring实战之抽象Bean和子Bean定义与用法示例

    Spring实战之抽象Bean和子Bean定义与用法示例

    这篇文章主要介绍了Spring实战之抽象Bean和子Bean定义与用法,结合实例形式分析了Spring抽象Bean和子Bean相关配置、定义与使用操作技巧,需要的朋友可以参考下
    2019-11-11
  • Eclipse远程debug的步骤与注意事项

    Eclipse远程debug的步骤与注意事项

    今天小编就为大家分享一篇关于Eclipse远程debug的步骤与注意事项,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-03-03
  • SpringBoot中的@FeignClient注解使用

    SpringBoot中的@FeignClient注解使用

    文章主要介绍了SpringCloud中的@FeignClient注解的使用及其参数详解,包括value/name、url、path、configuration、fallback/fallbackFactory、contextId等,通过@FeignClient注解,可以方便地声明一个REST客户端,并定义与目标服务通信的接口
    2024-11-11
  • springboot 使用 minio的示例代码

    springboot 使用 minio的示例代码

    Minio是Apcche旗下的一款开源的轻量级文件服务器,基于对象存储,协议是基于Apache License v2.0,开源可用于商务,本文给大家介绍下springboot 使用 minio的示例代码,感兴趣的朋友看看吧
    2022-03-03
  • 使用SpringBoot简单实现一个苹果支付的场景

    使用SpringBoot简单实现一个苹果支付的场景

    这篇文章主要为大家详细介绍了如何在Spring Boot项目中集成Apple Pay功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-11-11
  • Java中的system.getProperty()的作用及使用方法

    Java中的system.getProperty()的作用及使用方法

    System.getProperty() 方法用于获取系统属性的值,该方法接受一个字符串参数,表示要获取的系统属性的名称,返回值为字符串类型,表示该属性的值,接下来通过本文给大家介绍Java中的system.getProperty()的作用及使用方法,感兴趣的朋友跟随小编一起看看吧
    2023-05-05
  • Java Mybatis中的 ${ } 和 #{ }的区别使用详解

    Java Mybatis中的 ${ } 和 #{ }的区别使用详解

    这篇文章主要介绍了Mybatis中的 ${ } 和 #{ }的区别使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • 深入了解java内存分配和回收策略

    深入了解java内存分配和回收策略

    下面小编就为大家带来一篇深入了解java内存分配和回收策略。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-06-06

最新评论