什么是动态SQL?
动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句.
-
新建数据表blog
-
编写实体类对象
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
private int id;
private String title;
private String author;
private int views;
}
- 核心配置文件中注册mapper
<mapper class="com.dao.BlobMapper"></mapper>
- 需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
- BlogMapper.xml
<mapper namespace="com.dao.BlogMapper">
<select id="queryBlogIf" resultType="blog" parameterType="map">
select * from blog
<where>
<if test="title != null"> title = #{title} </if>
<if test="author != null"> and author = #{author} </if>
</where>
</select>
</mapper>
- 测试代码
@Test
public void test3(){
SqlSession session = MybatisUtils.getSession();
BlogMapper mapper = session.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title", "java是如此简单");
List<Blog> blogs = mapper.queryBlogIf(map);
for(Blog blog : blogs){
System.out.println(blog);
}
}
- 结果
Blog(id=4, title=Java是如此简单, createTime=Sun Oct 18 16:42:18 CST 2020, author=狂神, views=9999
- set语句
在这里插入代码片<!--注意set是用的逗号隔开-->
<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>
- choose语句:有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose
标签可以解决此类问题,类似于 Java 的 switch 语句
<select id="queryBlogChoose" parameterType="map" resultType="blog">
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>