zoukankan      html  css  js  c++  java
  • [mybatis]list的foreach的使用

    当传入参数为list的时候foreach的使用

    当参数为一个list的时候

    方法层:

         int deleteAll(List<String> list);
    

    xml文件中的sql语句

    <delete id="deleteAll" parameterType="list">
            delete from classify
            where id in
             <foreach collection="list" index="index" item="item" 
                  open="("  separator="," close=")">
                   #{item}  
              </foreach>
        </delete>
    

    当参数为多个list方法层

    控制层:

    执行层

    xml文件

    基本完成

    下面是一些常识:

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

    item表示集合中每一个元素进行迭代时的别名,
        index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,
        open表示该语句以什么开始,
        separator表示在每次进行迭代之间以什么符号作为分隔 符,
        close表示以什么结束

    collection主要有一下3种情况:

    1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
        2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
        3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可

    1.单参数List的类型:


    上述collection的值为list,对应的Mapper是这样的
    public List dynamicForeachTest(List ids);
    测试代码:

    2.单参数array数组的类型

    1 <select id="dynamicForeach2Test" parameterType="java.util.ArrayList" resultType="Blog">
    2     select * from t_blog where id in
    3     <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
    4          #{item}
    5     </foreach>
    6 </select> 
    

    上述collection为array,对应的Mapper代码:
    public List dynamicForeach2Test(int[] ids);
    对应的测试代码

    3.自己把参数封装成Map的类型

    1 <select id="dynamicForeach3Test" parameterType="java.util.HashMap" resultType="Blog">
    2         select * from t_blog where title like "%"#{title}"%" and id in
    3          <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
    4               #{item}
    5          </foreach>
    6 </select>
    

    上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
    public List dynamicForeach3Test(Map params);
    对应测试代码

    版权声明:本文为CSDN博主「withawind」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/withawind/article/details/87252769

  • 相关阅读:
    【LeetCode】Rotate Image
    【LeetCode】Combinations
    【LeetCode】Minimum Depth of Binary Tree
    【LeetCode】Reverse Nodes in k-Group
    【LeetCode】Reverse Linked List II
    【LeetCode】Insert Interval
    【LeetCode】Insertion Sort List
    python之列表生成式
    python 模块和模块sys.argv
    python 异常处理
  • 原文地址:https://www.cnblogs.com/anycc/p/13326224.html
Copyright © 2011-2022 走看看