动态SQL
什么是动态SQL:动态SQL就是根据不同条件生成不同的SQL语句
这一特性可以彻底摆脱这种痛苦
动态SQL元素和JSTL或基于类似的XML文本处理器相似。在Mybatis之前的版本中,有很多元素需要花时间了解。Mybatis 3大大精简了元素种类,现在只需要学习原来一半的元素便可。MyBatis采用功能强大的基于OGNL的表达式来淘汰其他大部分元素。
if
choose(when, otherwise)
trim (where,set)
foreach
环境搭建
CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建一个基础过工程
- 导包
- 编写配置文件
- 编写实体类
- 编写实体类对应Mapper接口和Mapper.xml
动态SQL的元素
元素 | 作用 | 备注 |
---|---|---|
if | 判断语句 | 单条件分支判断 |
choose(when、otherwise) | 相当于Java中的switch和case语句 | 多条件分支判断 |
trim(where、set) | 辅助元素,用于处理待定的SQL拼装问题,比如去掉多余的and、or元素 | 用于处理SQL拼装的问题 |
foreach | 循环语句 | 在in语句等列举条件常用 |
IF
多个符合条件时都会加入SQL
<select id="queryBlogIF" parameterType="map" resultType="blog">
select *from mybatis.blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author !=null">
and author = #{author}
</if>
</select>
Choose(When,Otherwise)
只会选择第一个符合条件的sql进行查询
<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>
Trim(Where,Set)
多个条件拼接sql查询
<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>
<update id="updateBlog" parameterType="map">
update mybatis.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片段
有的时候,可以将一部分功能抽取出来,方便复用
使用SQL标签抽取公共部分
<sql id="if-title-author"> <if test="title != null"> and title = #{title} </if> <if test="author !=null"> and author = #{author} </if> </sql>
在需要使用的地方使用include标签即可
<select id="queryBlogIF" parameterType="map" resultType="blog">
select *from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
注意事项
- 最好基于单表来定义SQL片段
- 不要存在where标签
- 一般复用if即可
Foreach
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id = #{id}
</foreach>
</where>
</select>
动态SQL就是在拼接SQL,我们只要保证SQL的正确性,按照SQL的格式去排列组合即可
collection对应的就是传递进来的参数名字,可以是数组、List、Set等集合
动态SQL就是在拼接SQL,我们只要保证SQL的正确性,按照SQL的格式去排列组合即可
collection对应的就是传递进来的参数名字,可以是数组、List、Set等集合
建议:
- 先在Mysql中写完整的SQL,再对应的修改成需要的动态SQL