1. 程式人生 > >Mybatis遍歷查詢 ——foreach

Mybatis遍歷查詢 ——foreach

變量 path ued pan oid open 返回 int pre

第一步:

  在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); } }

Mybatis遍歷查詢 ——foreach