什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
创建一个基础工程
1:导包
2:编写配置文件
3:创建一个实体类
@Data
@SuppressWarnings("all") //镇压警告
public class Blog {
private String id;
private String title;
private String author;
private Date createTime; //属性名和字段名不一致
private int views;
}
4:编写实体类的Mapper接口和 Mapper.xml文件
public interface BlogMapper {
//插入数据;
int addBlog(Blog blog);
}
insert into mybatis.blog (id, title, author, create_time, views) values (#{id}, #{title}, #{author}, #{createTime}, #{views});
5:测试运行OK
ifchoose (when, otherwise)select * from mybatis.blog where 1=1 and title = #{title} and author = #{author}
MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
trim,(where ,set)update mybatis.blog where id = #{id} title = #{title}, author = #{author}
where 元素只会在子元素返回任何内容的情况下才插入 “WHERe” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
所谓的动态的SQL,本质还是SQL语句,只不过我们是在SQL层面,去执行一个逻辑代码;
If
where
set
when
choose
title = #{title}, author = #{author}
有的时候,我们可以将一些功能抽取出来,方便利用;
1:使用SQL标签抽取公共的部分
2:在需要使用的地方使用include标签引用即可;在where标签里面
注意事项:
最好基于单表定义SQL片段
不要存在where标签
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
先在MySql中写完整的sql语句,在对应的修改成我们的动态的SQL实现通用即可;
动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。



