mybatis动态sql
Posted swaggyC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis动态sql相关的知识,希望对你有一定的参考价值。
动态sql是mybatis的特色功能,所谓动态sql,就是支持sql语句的动态拼接,从而使sql语句的使用更加灵活,使代码简洁可复用。
以下就常用的动态sql用法做一些总结。
- if :通过对参数的判断,动态地插入查询条件
<select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> </select>
- choose when otherwise 多选一,相当于if else
<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>
3.trim where set 智能得插入 where and set ,等关键字,注意where与and配合使用,而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>
<trim prefix="WHERE" prefixOverrides="AND |OR "> ... </trim>
<update id="updateAuthorIfNecessary"> update Author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set> where id=#{id} </update>
<trim prefix="SET" suffixOverrides=","> ... </trim>
4.foreach 遍历集合参数
<select id="selectPostIn" resultType="domain.blog.Post"> SELECT * FROM POST P WHERE ID in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select>
以上是关于mybatis动态sql的主要内容,如果未能解决你的问题,请参考以下文章
Mybatis -- 动态Sql概述动态Sql之<if>(包含<where>)动态Sql之<foreach>sql片段抽取
mybatis动态sql之利用sql标签抽取可重用的sql片段
MYBATIS05_ifwherechoosewhentrimsetforEach标签sql片段