什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
基本流程
1,数据库准备一张表
2,导包
3,编写核心配置文件
4,编写实体类
5,编写实体类对应的Mapper和Mapper.xml文件
6,在核心配置文件中注册Mapper.xml
7,测试
开启自动驼峰命名规则映射
<!--开启驼峰命名映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
即在数据库中为create_time对应Java实体类属性createTime
IF,Where
<select id="queryListIf" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
Where的作用:当至少有一个满足条件时添加Where,且会判断后面加的第一条语句,若是and开头,则会自动将这个and删除
本质上还是在拼接SQL,上述当没有满足条件时查询blog表中的所有,当满足条件时,则拼接SQL
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>
Set的作用:至少有一个满足条件时添加Set,且会判断后面加的最后的语句,若是",“结尾,则会自动将这个”,"删除
Choose(when,otherwise)
<select id="queryNoLimit" 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 `view` = #{view}
</otherwise>
</choose>
</where>
</select>
choose(when,otherwise)类似与Java中的switch(case,default),choose进入选择,when当什么什么时,进行条件判断,若满足条件,则执行条件中的内容,后面的when,otherwise将不再执行,otherwise当所有when都不满足条件时执行
ForEach
<select id="queryBlogById" parameterType="map" resultType="blog">
select * from blog
<where>
<foreach collection="ids" item="id" open="(" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
上述为,一个集合ids存储id的内容,根据这个集合查询所包含的id,open为开始,close为结束,separator为分隔符
才用map.put(“ids”,list)的方式导入集合
建议:现在Mysql中写出完整的sql,再对应的去修改即可
SQL片段
将一些功能的部分抽取出来方便复用
使用SQL标签抽取公共的部分
<sql id="titleAuthor">
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
在需要的地方使用include标签引用即可
<select id="queryListIf" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="titleAuthor"></include>
</where>
</select>
注意事项:
1.最好基于单表来定义SQL片段
2.不要存在where标签
总结
所谓的动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式去排列组合就可以了