什么是动态SQL??
MyBatis通过使用if,choose (when, otherwise),trim (where, set),foreach等标签可以组成非常灵活的SQL语句。
目的:先看懂动态SQL,能不能熟练使用以后再说
if
不会有人不知道if吧(滑稽)
最常见的场景是根据条件包含where子句的一部分
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE 1=1
<if test="title != null">
AND title like #{title}
</if>
</select>
为什么有1=1呢?
为了正确,如果if不成立,SQL语句最后跟了个where。。。,这可以等后面的where标签解决
if标签里的test属性就是判断条件
choose、when、otherwise
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
trim、where、set
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
这啥啊,怎么还有where标签
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
如果你想要自己指定规则,还可以使用trim标签
<trim prefix="WHERE" prefixOverrides="AND |OR ">
</trim>
意义:当WHERE后紧随AND或则OR的时候,就去除AND或者OR
<update id="updateUser" parameterType="com.dy.entity.User">
update user set
<if test="name != null">
name = #{name},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="age != null">
age = #{age}
</if>
<where>
<if test="id != null">
id = #{id}
</if>
and deleteFlag = 0;
</where>
</update>
看一哈,如果只有第一个if触发了,SQL语句变为update set name = #{name}, where … 。多了个逗号,这时候set标签来了,也可以自定义
的,这时候,就可以用mybatis为我们提供的set 标签了。下面是通过set标签改造后:
<update id="updateUser" parameterType="com.dy.entity.User">
update user
<set>
<if test="name != null">name = #{name},</if>
<if test="password != null">password = #{password},</if>
<if test="age != null">age = #{age},</if>
</set>
<where>
<if test="id != null">
id = #{id}
</if>
and deleteFlag = 0;
</where>
</update>
用trim表示为:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
WHERE是使用的 prefixOverrides(前缀), SET是使用的 suffixOverrides (后缀),懂我意思吧
foreach
常见于对集合遍历
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
<where>
<foreach item="item" index="index" collection="list"
open="ID in (" separator="," close=")" nullable="true">
#{item}
</foreach>
</where>
</select
bind
ind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。比如:
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
</select>
理解了吗?(我是没理解,得靠熟练度慢慢理解,不急,接受新的概念还是很难的)