MyBatis Foreach标签

关于之前的trim标签 其作用在于可以自定义一个标签用于覆盖除去特定的字符 就如where标签 可以对and|or进行除去。

以下是sql片段 主要是利用<sql>标签
将之前的动态sql改变 示例:

    <sql id="choose-when">
        <choose>
            <when test="title!=null">
                title=#{title}
            </when>
            <when test="author!=null">
                author=#{author}
            </when>
            <otherwise>
                views=#{views}
            </otherwise>
        </choose>
    </sql>
    
    <select id="querybywant" parameterType="map" resultType="com.pojo.Blog">
        select * from Blog
   <where>
   <include refid="choose-when"></include>
   </where>
    </select>

sql标签同样是实现内容的复用 比起每一语块都要用到同一语句 又得重复编写 很是麻烦。

ForEach的编写细节:
示例代码:

<select id="foreach_test" parameterType="map" resultType="com.pojo.Blog">
    select * from Blog
<where>
<foreach collection="ids" item="id"
   open="and (" separator="or" close=")"
>
    id=#{id}
</foreach>
</where>
</select>

测试代码:

    @Test
    public void foreach_test ()
    {
        SqlSession session=MyBatisTool.getSqlSession();
        Blogmapper blogmapper=session.getMapper(Blogmapper.class);
        HashMap<String,List> hashMap=new HashMap<>();
        List<Integer> list=new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        hashMap.put("ids",list);
        List<Blog> list_2=blogmapper.foreach_test(hashMap);
         for (Blog blog :list_2 ) {
             System.out.println(blog);
         }
        session.close();
    }

官方文档的原型 ForEach语句:

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

对照其测试代码段 白话解读:
collection="list" 该list是hashmap中的key 其value是创建的集合对象 需要给foreach标签一个作为集合参数传递,结合之前jstl的基础 那么item="item"容易理解得多——当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值——通过#{}取值即可。

open=“ID in (” separator=“,” close=")"这一部分照着 SQL代码理解会更好:

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

编写后:

open="and (" separator="or" close=")"

提示:一般的查询语句在接口中写方法时 其类型一般都为List 。在结合choose when 等等语句时 会出现异常 比如查询对象过多。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值