foreach 的主要用在构建in条件中,它可以在SQL语句中举办迭代一个荟萃。
foreach 元素的属性主要有 item,index,collection,open,软件开发,separator,close。
在利用 foreach 的时候最要害的也是最容易堕落的就是 collection 属性,该属性是必需指定的,可是在差异环境 下,该属性的值是纷歧样的,主要有一下3种环境:
下面别离来看看上述三种环境的示例代码:
1.单参数 List 的范例:
<select id="dynamicForeachTest" resultType="Blog"> select * from t_blog where id in <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
上述 collection 的值为list,对应的 Mapper 是这样的
public List<Blog> dynamicForeachTest(List<Integer> ids);
测试代码:
@Test public void dynamicForeachTest() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(3); ids.add(6); List<Blog> blogs = blogMapper.dynamicForeachTest(ids); for (Blog blog : blogs) System.out.println(blog); session.close(); }
2.单参数array数组的范例:
<select id="dynamicForeacpTest" resultType="Blog"> select * from t_blog where id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
上述collection为array,对应的Mapper代码:
public List<Blog> dynamicForeacpTest(int[] ids);
对应的测试代码:
@Test public void dynamicForeacpTest() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); int[] ids = new int[] {1,3,6,9}; List<Blog> blogs = blogMapper.dynamicForeacpTest(ids); for (Blog blog : blogs) System.out.println(blog); session.close(); }
3.本身把参数封装成Map的范例
<select id="dynamicForeacpTest" resultType="Blog"> select * from t_blog where title like "%"#{title}"%" and id in <foreach collection="ids" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
上述collection的值为ids,是传入的参数Map的key,对应的Mapper代码:
public List<Blog> dynamicForeacpTest(Map<String, Object> params);
对应测试代码:
@Test public void dynamicForeacpTest() { SqlSession session = Util.getSqlSessionFactory().openSession(); BlogMapper blogMapper = session.getMapper(BlogMapper.class); final List<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); ids.add(3); ids.add(6); ids.add(7); ids.add(9); Map<String, Object> params = new HashMap<String, Object>(); params.put("ids", ids); params.put("title", "中国"); List<Blog> blogs = blogMapper.dynamicForeacpTest(params); for (Blog blog : blogs) System.out.println(blog); session.close(); }