mybatis动态sql语句是基于OGNL表达式的,主要有以下几类:
-
if 语句 (判断语句)
-
choose、when、otherwize(分支语句,相当于java语言中的switch)
-
where (动态的添加"WHERE"关键字,并且可以智能的处理SQL语句中多余的"AND"与"OR"关键字)
-
set (在更新语句中动态的添加"SET"关键字,并且可以智能的处理SQL语句中多余的",")
-
foreach (用户遍历容器)
-
trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)
if标签语句
if标签用来实现根据条件拼接sql语句,下面示例用来判断参数如果不为null,则拼接sql
<select id="findByCondition" parameterType="student">
SELECT * FROM student WHERE 1 = 1
<if test="studentNo != null">
studentNo = #{studentNo}
</if>
<if test="studentName != null">
AND studentName = #{studentName}
</if>
<if test="sex != null">
AND sex = #{sex}
</if>
<if test="birthday != null">
AND birthday = #{birthday}
</if>
</select>
上述sql中,如果studentNo为null,则拼接出来的sql为:
SELECT * FROM student WHERE 1 = 1
AND studentNo = ?
AND studentName = ?
AND sex = ?
AND birthday = ?
解决这个问题,需要用到where标签
where标签语句
where标签只有在存在一个及以上的if条件为真的情况下才去插入"WHERE"子句。而且,若最后的内容是"AND"或"OR"开头的,where标签可以智能的将它们去除。
<select id="findByCondition" parameterType="student">
SELECT * FROM student
<where>
<if test="studentNo != null">
studentNo = #{studentNo}
</if>
<if test="studentName != null">
AND studentName = #{studentName}
</if>
<if test="sex != null">
AND sex = #{sex}
</if>
<if test="birthday != null">
AND birthday = #{birthday}
</if>
</where>
</select>
set标签语句
set标签是用在更新操作的时候,功能和where标签元素差不多,set标签会动态前置"SET"关键字,同时也会删掉无关的逗号。
<update id="update" parameterType="Student">
UPDATE student
<set>
<if test="studentName != null">
studentName = #{studentName},
</if>
<if test="sex != null">
sex = #{sex},
</if>
<if test="birthday != null">
birthday = #{birthday}
</if>
</set>
WHERE studentNo = #{studentNo}
</update>
trim标签语句
mybatis的trim标签一般用于去除sql语句中多余的"ADN"、逗号、或者给sql语句前拼接"WHERE"、“SET"以及"values(” 等前缀,或者添加")"等后缀,可用于选择性插入、更新、删除或者条件查询等操作。
trim标签中涉及到的属性如下:
属性 | 描述 |
---|---|
prefix | 给sql语句拼接的前缀 |
suffix | 给sql语句拼接的后缀 |
prefixOverrides | 去除sql语句前面的关键字或者字符,该关键字或者字符由prefixOverrides属性指定,假设该属性指定为"AND",当sql语句的开头为"AND",trim标签将会去除该"AND" |
suffixOverrides | 去除sql语句后面的关键字或者字符,该关键字或者字符由suffixOverrides属性指定 |
trim标签的案例如下:
<insert id="save" parameterType="Student">
INSERT INTO student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="studentNo != null">
studentNo,
</if>
<if test="studentName != null">
studentName,
</if>
<if test="sex != null">
sex,
</if>
<if test="birthday != null">
birthday
</if>
</trim>
<trim prefix="VALUES(" suffix=")" suffixOverrides=",">
<if test="studentNo != null">
#{studentNo},
</if>
<if test="studentName != null">
#{studentName},
</if>
<if test="sex != null">
#{sex},
</if>
<if test="birthday != null">
#{birthday}
</if>
</trim>
</insert>