zoukankan      html  css  js  c++  java
  • 19、mybatis学习——mybatis的动态sql之<foreach>遍历传入的数组,集合和map

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

    • 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对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 ③除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果User有属性List ids。入参是User对象,那么这个collection = "ids".如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"

    在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况: 

    • 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list .
    • 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array .
    • 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.

    举例一(根据id批量查询):

    Student.java

    StudentMapper接口中定义方法

     StudentMapper的配置文件配置

         <select id="getStuByForeachId" resultType="student">
             select * from student where id in
             <!-- collection:指定要遍历的集合
                     item:将当前遍历出的元素赋值给指定变量
                     separator:每个元素之间的分隔符
                     open:遍历出所有结果拼接一个开始的字符
                     close: 遍历出所有结果拼接一个结尾的字符
                     index:索引。遍历list和数组时,index是元素的序号
                         遍历map的时候,index是元素的key;
                     #{变量名}就能取出变量的值也就是当前遍历出的元素-->
             <foreach collection="ids" item="id" 
                     separator="," open="(" close=")">
                 #{id}
             </foreach>
         </select>

    测试方法

        //测试通过<foreach>遍历参数ids
        @Test
        public void testGetStuByForeachId() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            List<Integer> ids = new ArrayList<Integer>();
            ids.add(1);
            ids.add(2);
            ids.add(4);
            List<Student> stus = studentMapper.getStuByForeachId(ids);
            System.out.println(stus);
            sqlSession.close();
        }

    测试结果

    举例二(批量插入数据)

      StudentMapper接口中定义方法

      StudentMapper配置文件进行配置

         <!-- 通过foreach批量插入数据 -->
         <insert id="insertStusByForeach">
             insert into student(name,c_id) values
             <foreach collection="stus" item="stu" separator=",">
                 (#{stu.name},#{stu.college.id})
             </foreach>
         </insert>

    测试方法:

        //测试通过<foreach>批量插入数据
        @Test
        public void testInsertStusByForeach() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            List<Student> stus = new ArrayList<>();
            stus.add(new Student(null, "小张", new College(1)));
            stus.add(new Student(null, "小李", new College(2)));
            studentMapper.insertStusByForeach(stus);
            sqlSession.commit();
            sqlSession.close();
        }

    测试结果

  • 相关阅读:
    Unity Shader (三)Surface Shader机制
    Unity Shader (二)Cg语言
    Unity Shader (一)ShaderLab 语法
    Pytorch笔记 (3) 科学计算2
    两种方法实现斐波那契数列
    根据输入的整数n使得输出精确到小数n位
    算法竞赛入门 —— 循环结构 习题
    Pytorch笔记 (3) 科学计算1
    算法竞赛入门 (一)语言篇 循环结构
    C++编译错误提示 [Error] name lookup of 'i' changed for ISO '
  • 原文地址:https://www.cnblogs.com/lyh233/p/12361392.html
Copyright © 2011-2022 走看看