• 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时要用$而不是#

  • 相关阅读:
    第6章——数据库的安全性
    手机app开发可选技术——React Native
    【第一阶段:java基础】第8章:面向对象编程高级-1(P333-P393)static、main、代码块、单例设计模式
    Ubuntu 22.10 (Kinetic Kudu) 发布
    MySQL触发器使用指南大全
    【Java】工具类的设计
    dvadmin-打包发布-nginx-静态服务器配置-防火墙设置
    利用IoDriverObjectType控制内核驱动加载
    Shell脚本之正则表达式详解
    Kubernetes集群部署
  • 原文地址:https://blog.csdn.net/weixin_43185154/article/details/126488849