1. 程式人生 > 實用技巧 >13、動態sql之Foreach

13、動態sql之Foreach

查詢前三條記錄:

使用sql:

select *
from blog
where (id = 1 or id = 2 or id = 3);

使用mybatis提供的foreach遍歷來寫:

  item:欄位id

  connection:集合

  open:開始

  close:結束

  separator:分隔符號

  [index]:開始下標

SELECT *
FROM blog b
WHERE id in
  <foreach item="id" index="index" collection="ids"
      open="(" separator="or" close
=")"> id = #{id} </foreach>

程式碼實現:

  dao層介面(定義方法)

    /**
     * 遍歷查詢部落格資訊
     */
    List<Blog> conditionQueryForeach(Map map);

  dao層介面實現類(Mapper.xml)

    <select id="conditionQueryForeach" parameterType="map" resultType="blog">
        select * from blog
        <
where> <foreach collection="ids" item="id" separator="or"> id = #{id} </foreach> </where> </select>

  測試類

    @Test
    public void conditionQueryForeachTest(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        BlogMapper mapper 
= sqlSession.getMapper(BlogMapper.class); Map map = new HashMap();
List
<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); map.put("ids",ids); List<Blog> blogs = mapper.conditionQueryForeach(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }

  list集合中傳入幾個id就查詢出幾個人的部落格資訊