Mybatis动态sql之foreach

foreach标签是对集合进行遍历(尤其是在构建 IN 条件语句的时候)
注意事项:属性中collection是声明遍历集合的名字,当使用可迭代对象或者数组时,index 属性是当前迭代的序号,item 属性的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。open属性是起始拼接的值,separator是中间需要分割的值,close是结束拼接时的值

foreach标签使用

  1. 接口类:
//根据条件查询
    List<Blog> query(Map map);
  1. Mapper.xml配置文件
   <sql id="selectBlog">
        select id,title,author,create_time,views from blog
    </sql>

<select id="query" parameterType="map" resultType="Blog">
    <include refid="selectBlog" />
        <where>
        <!--如果传入的集合的个数为0则不进行遍历 -->
            <if test="ids.size()!=0">
                id in
                <foreach collection="ids" index="index" item="id" open="(" separator="," close=")">
                <!--取值,取出集合中ids的值 -->
                    #{id}
                </foreach>
            </if>
        </where>
</select>
  1. 测试类:

当不传入遍历集合时,不会执行foreach标签语句

 @org.junit.Test
    public void test(){
    
    
        //通过封装好的工具类获取SqlSession会话
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //通过接口类型class获取接口对象实例(动态代理)
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        //执行接口中的方法
        HashMap<String,Object> map=new HashMap<String, Object>();
        //传入集合的名字为ids
        ArrayList<Integer> ids = new ArrayList<Integer>();
//        ids.add(1);
//        ids.add(2);
//        ids.add(3);
        map.put("ids",ids);
        mapper.query(map);
        sqlSession.commit();
        //关闭SqlSession
        sqlSession.close();
    }

结果:
在这里插入图片描述

当集合传入值时,此时会执行foreach语句进行循环遍历结果,而且会根据传入的值进行拼接,批量查询数据

集合中传入一个值时
在这里插入图片描述
集合中传入多个值时
在这里插入图片描述
动态sql的总结:其实动态 sql 语句的编写往往就是一个拼接的问题,为了保证拼接准确,我们最好首先要写原生的 sql 语句出来,然后在通过 mybatis 动态sql 对照着改,防止出错。多在实践中使用才是熟练掌握它的技巧。

猜你喜欢

转载自blog.csdn.net/weixin_45608165/article/details/113756887
今日推荐