动态SQL就是在拼接SQL语句,只要我么保证SQL得正确性,按照SQL的格式,去排列组合就可以了.
继上篇https://blog.csdn.net/m0_74135466/article/details/127997864?spm=1001.2014.3001.5501
// SQL片段
List<Blog> queryBlogIF1(Map map);
<!-- SQl片段
将一部分公共的Sql语句抽取出来放在<sql id=" ">标签中,
然后在需要使用SQL的地方使用include标签引用即可-->
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIF1" parameterType="map" resultType="blog">
select *from mybatis.blog where
<include refid="if-title-author"></include>
</select>
<!-- 注意:
1.最好基于单表来定义SQL片段
2.SQL标签内不要存在WHERE标签-->
Foreach:
// 查询1-2-3 号记录的博客
List<Blog> queryBlogForeach(Map map);
}
<!-- Foreach-->
<!-- 传递一个map,map中可以存在一个集合-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select *from mybatis.blog
<where>
<foreach collection="ids" item="id" open= "and (" close =")" separator="or">
id = #{id}
</foreach>
</where>
</select>
@Test
public void queryBlogforeach(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
// ids.add(2);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}