Mybatis遍歷查詢 ——foreach


第一步:

  在xxxMapper接口中添加一個函數,返回一個list,這里的參數是一個integer類型的集合

public List<Emp> findEmpByList(@Param("list") List<Integer> list);

第二步:

  在xxxMapper.xml 中添加statement語句(SQL語句)。

  如SQL語句:select * from employee where id in (1 ,2 , 3,4 ); 
<select id="findEmpByList" resultType="com.neuedu.bean.Emp">
        select * from employee where id in 
        <!-- select * from employee where id in ( , , , ); -->

<foreach collection="list" item="id" open="(" close=")" separator=","> #{id} </foreach> </select>

  foreach標簽中

    collection:指定要遍歷的集合
    item:將當前遍歷出的元素賦值給指定的變量
    separator:每個元素之間的分隔符
    open:遍歷出所有結果拼接一個開始的字符
    close:遍歷出所有結果拼接一個結束的字符

第三步:測試

@Test
    public void testFindEmpByList(){
  //獲取IOC容器 ApplicationContext ioc
=new ClassPathXmlApplicationContext("spring.xml");
//從IOC容器中獲取bean對象 EmployeeMapper bean
= ioc.getBean(EmployeeMapper.class);
//創建一個集合 List
<Integer> list=Arrays.asList(1,2,3);
//使用bean對象的方法 List
<Emp> findEmpByList = bean.findEmpByList(list); for (Emp emp : findEmpByList) { System.out.println(emp); } }

 


免責聲明!

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



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