MyBatis 动态SQL
Posted 耍流氓的兔兔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis 动态SQL相关的知识,希望对你有一定的参考价值。
MyBatis动态SQL:
动态SQL是在运行时生成和执行SQL的编程方法
动态是和静态相对而言的。静态SQL指的是在代码编译时刻就已经包含在代码中的那些已经充分明确的固定的SQL语句
MyBatis中的动态Sql是怎样设定的?如何使用?
MyBatis的动态SQL是基于OGNL表达式的,通过表达式进行判断,对sql进行灵活拼接、组装
常用的节点有:if、choose when otherwise、where、set、trim、foreach、sql片段等
1.1 if
<select id="selectActiveBlogByTitle" parameterType="Blog" resultMap="blogResultMap">
SELECT * FROM blog
WHERE state = ‘ACTIVE‘
<if test="title != null and title != ‘‘">
AND title LIKE #{title}
</if>
</select>
1.2 choose when otherwise
<!-- 几个查询条件互斥 -->
<select id="selectActiveBlogByTitleOrStyle" parameterType="Blog" resultMap="blogResultMap">
select * from blog
WHERE state = ‘ACTIVE‘
<choose>
<when test="title != null and title != ‘‘">
and lower(title) like lower(#{title})
</when>
<when test="style != null and style != ‘‘">
and style = #{style}
</when>
<otherwise>
and featured = true
</otherwise>
</choose>
</select>
1.3 where
<!-- where:
自动修补查询条件,查询语句中的 where 关键字使用 <where> 标签替代
注意:不能省略 and 或 or 关键字
-->
<select id="selectBlogByCondition" parameterType="Blog" resultMap="blogResultMap">
select * from blog
<where>
<if test="state != null and state != ‘‘">
state = #{state}
</if>
<if test="title != null and title != ‘‘">
and lower(title) like lower(#{title})
</if>
<if test="featured != null">
and featured = #{featured}
</if>
</where>
</select>
1.4 set
<!-- set: 会自动去掉语句后面多余的逗号 -->
<update id="upadteBlogByCondition" parameterType="Blog">
UPDATE
`blog`
<set>
<if test="title != null">`title` = #{title},</if>
<if test="authorId != null">`author_id` = #{authorId},</if>
<if test="state != null">`state` = #{state},</if>
<if test="featured != null">`featured` = #{featured},</if>
<if test="style != null">`style` = #{style} </if>
</set>
WHERE `id` = #{id}
</update>
1.4 trim
<!-- trim: trim可以实现set和where的功能 -->
<select id="selectBlogByConditionTrim" parameterType="Blog" resultMap="blogResultMap">
select * from blog
<trim prefix="where" prefixOverrides="and | or">
<if test="state != null and state != ‘‘">
state = #{state}
</if>
<if test="title != null and title != ‘‘">
and lower(title) like lower(#{title})
</if>
<if test="featured != null">
and featured = #{featured}
</if>
</trim>
</select>
1.5 foreach
<delete id="deleteBlogList" parameterType="list">
delete from blog where id in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</delete>
1.6 sql片段
<!-- sql片段 -->
<sql id="aliasColumn">
</sql>
<!-- 引用 -->
<include refid="aliasColumn">
</include>
以上是关于MyBatis 动态SQL的主要内容,如果未能解决你的问题,请参考以下文章
Mybatis -- 动态Sql概述动态Sql之<if>(包含<where>)动态Sql之<foreach>sql片段抽取
mybatis动态sql之利用sql标签抽取可重用的sql片段
MYBATIS05_ifwherechoosewhentrimsetforEach标签sql片段