• mybatis使用foreach


    foreach常用属性:

    collection:

    需做foreach的对象,作为入参时,list、array对象时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“paramName”)注解来设置自定义collection属性值,设置keyName后,list、array会失效;

    item: 集合元素迭代时的别名称,该参数为必选项

    index:map中代指key,其它时用于表示在迭代过程中,每次迭代到的位置

    separator:元素间的分隔符

    open:遍历集合开始时使用

    close:遍历集合结束时使用

    使用场景:

    1、collection为list时:

    1. <resultMap id="BaseResultMap" type="com.list.demo">
    2. <result column="id" property="id"/>
    3. <result column="name" property="name"/>
    4. <result column="age" property="age"/>
    5. <result column="gender" property="gender"/>
    6. <result column="address" property="address"/>
    7. resultMap>
    8. <select id="selectTestList1" resultMap="BaseResultMap">
    9. SELECT id, name, age, gender, address
    10. FROM test_01
    11. WHERE
    12. id in
    13. <foreach collection="ids" item="id" separator="," open="(" close=")">
    14. #{id}
    15. foreach>
    16. select>

    对应的Mapper接口为:List selectTestList1(@Param("ids")List ids);

    2、collection为array时:

    1. <select id="selectTestList2" resultMap="BaseResultMap">
    2. SELECT id, name, age, gender, address
    3. FROM test_01
    4. WHERE
    5. name in
    6. <foreach collection="names" item="name" separator="," open="(" close=")">
    7. #{name}
    8. foreach>
    9. select>

    对应的Mapper接口为:List selectTestList2(@Param("names")String[] names);

    3、collection为map时:

    1. <select id="selectTestList3" resultMap="BaseResultMap">
    2. SELECT id, name, age, gender, address
    3. FROM test_01
    4. WHERE
    5. (name, age) in
    6. <foreach collection="maps" item="v" index="k" separator="," open="(" close=")">
    7. (#{k}, #{v})
    8. foreach>
    9. select>

    对应的Mapper接口为:List selectTestList3(@Param("maps")Map maps);

    特别注意:当collection为list或array时,index代表的是当前序号

    比如:

    1. <foreach collection="list" item="item" index="i">
    2. <if test="i > 0">
    3. ${item[i-1]}=#{item}
    4. if>
    5. foreach>

    注意:用index时要用$而不是#

  • 相关阅读:
    单片机论文参考:1、基于单片机的电子琴
    【暑期每日一题】洛谷 P7694 [COCI2009-2010#4] AUTORI
    面向对象编程的六大原则
    275-I/O阻塞和非阻塞,同步和异步
    统计学习方法 决策树
    OpenCV+相机校准和3D重建
    SpringSecurity授权流程(自己做笔记用的)
    水中铅超标如何处理?除铅吸附材料
    Linux之fdisk的使用
    .NET 一款支持8种方式维持权限的工具
  • 原文地址:https://blog.csdn.net/weixin_43185154/article/details/126488849