foreach

  1. foreach元素的属性主要有 itemindexcollectionopenseparatorclose
  2. item:表示集合中每一个元素进行迭代时的别名,
  3. index:指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
  4. open:表示该语句以什么开始,
  5. separator:表示在每次进行迭代之间以什么符号作为分隔 符,
  6. close:表示以什么结束。
  7. collection
  8. 1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
  9. 单参数List的类型:
  10. 接口方法:public List dynamicForeachTest(List ids);
  11. <select id="dynamicForeachTest" parameterType="java.util.List" resultType="Blog">
  12. select * from t_blog where id in
  13. <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
  14. #{item}
  15. </foreach>
  16. </select>
  17. 2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  18. 单参数array数组的类型:
  19. 接口方法:public List dynamicForeach2Test(int[] ids);
  20. <select id="dynamicForeach2Test" parameterType="java.util.ArrayList" resultType="Blog">
  21. select * from t_blog where id in
  22. <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
  23. #{item}
  24. </foreach>
  25. </select>
  26. 3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可
  27. 参数封装成Map的类型:
  28. 接口方法:public List dynamicForeach3Test(Map params);
  29. <select id="dynamicForeach3Test" parameterType="java.util.HashMap" resultType="Blog">
  30. select * from t_blog where title like "%"#{title}"%" and id in
  31. <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
  32. #{item}
  33. </foreach>
  34. </select>
  35. 4.实际开发使用
  36. 接口方法:List<Map<String,Object>> selectFileListByDir(@Param("params") Map<String, String> params);
  37. <select id="selectFileListByDir" resultType="java.util.Map" parameterType="hashmap">
  38. SELECT * FROM RTOC_FILE_SYSTEM WHERE
  39. <foreach collection="params" index="key" item="value" separator="AND">
  40. <choose>
  41. <when test='key=="startTime"'>
  42. UPLOAD_DATE >= to_date(#{value},'yyyy-MM-dd hh24:mi:ss')
  43. </when>
  44. <when test='key=="endTime"'>
  45. UPLOAD_DATE &lt;= to_date(#{value},'yyyy-MM-dd hh24:mi:ss')
  46. </when>
  47. <when test='key=="UPLOAD_USER"'>
  48. ${key} = #{value}
  49. </when>
  50. <otherwise>
  51. ${key} like '%' || #{value} || '%'
  52. </otherwise>
  53. </choose>
  54. </foreach>
  55. ORDER BY UPLOAD_DATE DESC
  56. </select>