19、mybatis學習——mybatis的動態sql之 遍歷傳入的數組,集合和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();
    }

測試結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM