foreach

Another common necessity for dynamic SQL is the need to iterate over a collection, often to build an IN condition. For example:

  1. <select id="selectPostIn" resultType="domain.blog.Post">
  2. SELECT *
  3. FROM POST P
  4. <where>
  5. <foreach item="item" index="index" collection="list"
  6. open="ID in (" separator="," close=")" nullable="true">
  7. #{item}
  8. </foreach>
  9. </where>
  10. </select>

The foreach element is very powerful, and allows you to specify a collection, declare item and index variables that can be used inside the body of the element. It also allows you to specify opening and closing strings, and add a separator to place in between iterations. The element is smart in that it won’t accidentally append extra separators.

NOTE You can pass any Iterable object (for example List, Set, etc.), as well as any Map or Array object to foreach as collection parameter. When using an Iterable or Array, index will be the number of current iteration and value item will be the element retrieved in this iteration. When using a Map (or Collection of Map.Entry objects), index will be the key object and item will be the value object.

This wraps up the discussion regarding the XML configuration file and XML mapping files. The next section will discuss the Java API in detail, so that you can get the most out of the mappings that you’ve created.