什么是动态sql?
动态sql就是指根据不同的条件生成不同的sql语句
创建一个基础工程
- 导包
- 编写配置文件
- 编写实体类
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
- 编写实体类对应的Mapper接口和Mapper.xml
public interface BlogMapper {
//插入数据
int addBlog(Blog blog);
//查询博客
List<Blog> queryBlogIf(Map map);
}
IF语句:
where标签:where 元素只会在至少有一个子元素的条件返回 SQL 子句的情况下才去插入“WHERE”子句。而且,若语句的开头为“AND”或“OR”,where 元素也会将它们去除。
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
@org.junit.Test
public void test2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
@org.junit.Test
public void test3(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("author","小红");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
CHOOSE语句:
相当于java中的switch-case语句,满足多个条件时也只能拼接一个when中的语句,都不满足时拼接otherwise里的语句
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">and title = #{title}</when>
<when test="author != null">and author = #{author}</when>
<otherwise>and views = #{views}</otherwise>
</choose>
</where>
</select>
set标签:set 元素会动态前置 SET 关键字,同时也会删掉无关的逗号,因为用了条件语句之后很可能就会在生成的 SQL 语句的后面留下这些逗号。
SQL片段:
有的时候,我们可能会将一些sql代码抽取出来,方便复用
使用:
使用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="queryBlogIF" parameterType="map" resultType="com.rui.pojo.Blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意:
- 最好基于单表来定义sql
- 最好不要添加where标签
动态sql建议:
现在mysql中写出完整的sql语句,再慢慢修改为动态sql语句