MyBatis动态SQL:foreach

关于动态SQL另外一个常用的操作就是需要对一个集合进行遍历,通常发生在构建IN条件语句时:
1.mapper.xml
  1. <select id="selectEmployeeIn" resultType="org.fkit.domain.Employee">
  2. SELECT * FROM tb_employee WHERE ID IN
  3. <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
  4. #{item}
  5. </foreach>
  6. </select>
    <select id="selectEmployeeIn" resultType="org.fkit.domain.Employee">
        SELECT * FROM tb_employee WHERE ID IN
        <foreach item="item" index="index" collection="list" open="(" separator="," close=")">
            #{item}
         </foreach>
    </select>
2.mapper.java
  1. List<Employee> selectEmployeeIn(List<Integer> ids);
List<Employee> selectEmployeeIn(List<Integer> ids);
3.controller
  1. @GetMapping("/mysql/DynamicSQL/foreach")
  2. public void dynamicSQLForeach()
  3. {
  4. //获得SqlSession实例
  5. SqlSession sqlSession = FKSqlSessionFactory.getSqlSession();
  6. //获得Mapper接口代理对象
  7. EmployeeMapper em = sqlSession.getMapper(EmployeeMapper.class);
  8. //创建List
  9. List ids = new ArrayList<Integer>();
  10. ids.add(1);
  11. ids.add(3);
  12. //获取查询结果
  13. List<Employee> list = em.selectEmployeeIn(ids);
  14. list.forEach(one -> System.out.println(one.getName()));
  15. }
    @GetMapping("/mysql/DynamicSQL/foreach")
    public void dynamicSQLForeach()
    {
        //获得SqlSession实例
        SqlSession sqlSession = FKSqlSessionFactory.getSqlSession();
        //获得Mapper接口代理对象
        EmployeeMapper em = sqlSession.getMapper(EmployeeMapper.class);
        //创建List
        List ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(3);
        //获取查询结果
        List<Employee> list = em.selectEmployeeIn(ids);
        list.forEach(one -> System.out.println(one.getName()));
    }
4.输出