1.SQL片段
有的时候,我们可能会将一些相同的sql抽取出来,方便复用,抽取出来的sql就叫做SQL片段
如下:
<!--sql片段-->
<sql id="if-sql">
<if test="title != null">
and title like concat('%',#{title},'%')
</if>
</sql>
<select id="queryBlogIF" resultType="com.sun.pojo.Blog" parameterType="map">
select * from blog where 1 = 1
<include refid="if-sql"/>
</select>
注意:
- 最好基于单表来定义SQL片段,不要有太过复杂的SQL语句
- 不要存在where标签
2.Foreach标签
2.1.引入
foreach标签可以对一个集合进行遍历,通常是在构建in条件语句的时候
<select id="queryBlogForeach" resultType="com.sun.pojo.Blog" parameterType="Map">
select * from blog where id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</select>
属性:
注意:括号里的是以本次情况为例
collection:要遍历的集合(要和HashMap里的key值保持一致)
item:遍历出来的元素的名称(要和#{}里的一致)
open:遍历开始前拼接的SQL
close:遍历结束后拼接的SQL
separator:分隔符
2.2.测试类:
@Test
public void selectForEachTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap hashMap = new HashMap();
ArrayList<Integer> idss = new ArrayList<>();
idss.add(1);
idss.add(2);
hashMap.put("ids",idss);
List<Blog> blogs = mapper.queryBlogForeach(hashMap);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
拼接好的SQL如下: