动态sql 就是指 根据不同的条件生成不同的sql
拓展 UUID 唯一的随机数
用法 封装到工具类中 要用可以直接调用
package com.mumu.util;
import java.util.UUID;
public class Uuid {
public static String getuuid(){
//把 - 去掉
String s = UUID.randomUUID().toString().replaceAll("-", "");
return s;
}
}
动态sql 我们来先了解
<if test="条件表达式 " > sql语句 </if>
if标签 就是判断的意思 如果test=“ 条件表达式成立”
那么将执行 后面的sql语句
<select id="getbolg" parameterType="map" resultType="blog">
select * from mybatis.blog where
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</select>
但是由于条件的不缺定性 条件不同时 where后面不知道要不要接and或者or
所以我们一般在使用筛选时 都用个where标签 把它们包主
<select id="getbolg" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title!=null">
title=#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</where>
</select>
choose、when、otherwise 标签
/** choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。
当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。类似于Java 的 switch 语句,
# choose 为 switch,when 为 case,otherwise 则为 default。 -->*/
` <select id="getbolg" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title!=null">
title=#{title}
</when>
<otherwise>
</otherwise>
</choose>
</where>
</select>``
trim、where、set 标签
由于不知道什么时候要用set 设置修改数据库 所以我们直接用set标签的形式
将它们包住 直接不用写set字段
<update id="update" parameterType="map">
update mybatis.blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="author!=null">
author=#{author},
</if>
<if test="views!=null">
views=#{views}
</if>
</set>
where id=#{id}
</update>