动态的SQL
if动态查询(可以实现多个条件查询)
必须要有where 1=1
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog where 1=1
<if test="title!=null">
and title = #{title}
</if>
<if test="author!=null">
and author = #{author}
</if>
</select>
@Test
public void test2() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, String> map = new HashMap<>();
map.put("author", "闫老师");
map.put("title", "世界如此简单");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
choose(when otherwise)
会选择一个when执行 执行之后不会再执行后面的
<select id="queryBlogChoose" resultType="blog" parameterType="map">
select * from blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<when test="author!=null">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
trim(where set)
where 1=1 替换成 标签 where标签 如果是第一个会默认把and去掉
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<if test="title!=null">
and title = #{title}
</if>
<if test="author!=null">
and author = #{author}
</if>
</where>
</select>
set标签 配合update使用 存在多余的‘,’会直接去掉
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author},
</if>
</set>
where id=#{id}
</update>
所谓的动态的sql,本质还是sql语句,只是我们可以在sql层面,去执行一个逻辑代码
sql片段
有的时候,我们可以会将一些功能的部分抽取出来,方便复用
1.使用sql标签抽取公共的部分
<sql id="if-title-author">
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
2.在需要使用的地方使用include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意事项
- 最好基于单表来定义SQL片段
- SQL不要存在where标签 set标签(代码的复用性不好)
foreach
<!--
select * from blog where 1=1 and ( id=1 or id =2 or id=3)
用万能的map进行传递 者map可以是一个集合
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" open=" ( " separator="or" close=" ) " item="id">
id=#{id}
</foreach>
</where>
</select>