关于之前的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="">
select * from Blog
<where>
<include refid="choose-when"></include>
</where>
</select>
sql标签同样是实现内容的复用 比起每一语块都要用到同一语句 又得重复编写 很是麻烦。
ForEach的编写细节:
示例代码:
<select id="foreach_test" parameterType="map" resultType="">
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="">
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 对象(或者 对象的集合)时,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 等等语句时 会出现异常 比如查询对象过多。