一、SQL片段
有的时候,我们可能会将一些功能的部分抽取出来,方便使用。
- 使用SQL标签抽取公共部分
- 在需要使用的地方使用include标签引用即可
1.1、接口
List<Blog> queryBlogIF(Map map);
1.2、Mapper
<sql id="if-title-author">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
1.3、测试
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title" , "Java如此简单2");
map.put("author" , "孤冬");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs){
System.out.println(blog);
}
sqlSession.close();
}
1.4、效果

注意:
- 最好基于单表来定义SQL片段
- 不要存在where标签
二、Foreach
2.1、接口
//查询第1-2-3号记录的博客
List<Blog> queryBlogForeach(Map map);
2.2、Mapper
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="and(" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
2.3、测试
@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();
}
2.4、效果

三、总结
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了!
建议:
先在Mysql中写出完整的SQL语句,再去对应的修改成为我们的动态SQL实现即可。
本文介绍了Mybatis中如何使用SQL片段和Foreach标签提高代码复用性。SQL片段允许抽取出公共部分,通过include标签引用,而Foreach用于动态SQL的构建,尤其在处理列表参数时非常实用。文章通过接口、Mapper和测试案例详细阐述了这两个功能的使用方法和注意事项。
646

被折叠的 条评论
为什么被折叠?



