<foreach> 元素主要用在构建 in 条件中,它可以在 SQL 语句中迭代一个集合。
<foreach> 元素的属性主要有 item、index、collection、open、separator、close。
在使用 <foreach> 元素时,最关键、最容易出错的是 collection 属性,该属性是必选的,但在不同情况下该属性的值是不一样的,主要有以下 3 种情况:
在 myBatisDemo03 应用中测试 <foreach> 元素,具体过程如下:
在 com.mybatis 包的 UserMapper.xml 文件中添加如下 SQL 映射语句:
- <!--使用foreach元素查询用户信息-->
- <select id="selectUserByForeach" resultType="com.po.MyUser" parameterType=
- "List">
- select * from user where uid in
- <foreach item="item" index="index" collection="list"
- open="(" separator="," close=")">
- # {item}
- </foreach>
- </select>
在 com.dao 包的 UserDao 接口中添加如下数据操作接口方法:
在 com.controller 包的 UserController 类中添加如下程序调用数据操作接口方法。
- //使用foreach元素查询用户信息
- List<Integer> listId=new ArrayList<Integer>();
- listId.add(34);
- listId.add(37);
- List<MyUser> listByForeach = userDao.selectUserByForeach(listId);
- System.out.println ("foreach元素================");
- for(MyUser myUser : listByForeach) {
- System.out.println(myUser);
- }
运行 com.controller 包中的 TestController 主类,测试动态 SQL 语句。