关于动态SQL另外一个常用的操作就是需要对一个集合进行遍历,通常发生在构建IN条件语句时:
1.mapper.xml
<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>
- <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>
<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
List<Employee> selectEmployeeIn(List<Integer> ids);
- List<Employee> selectEmployeeIn(List<Integer> ids);
List<Employee> selectEmployeeIn(List<Integer> ids);
3.controller
@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()));
}
- @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()));
- }
@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.输出