标签:
# if
# choose(when,otherwise)
# trim(where,set)
# foreach
动态SQL之<if>标签
动态sql最常见的使用场景是if搭配where来进行描写.
<select id="findBlogWithTitle" resultType="Blog">
select * from Blog where state='ACTIVE'
<if test="title != null">
AND tilte like #{title}
</if>
</select>
本条语句实现一个基本的查找功能.如果不传入title,所有处于ACTIVE状态的Blog都会返回.如果传入的title不为空,则会对title一列进行模糊查询
<select id="findBlogLike" resultType="Blog">
select * from Blog where state="ACTIVE"
<if test = "title != null">
AND title like #{title}
</if>
<if test ="title != null and autor.name != null">
AND author_name like #{author.name}
</if>
</select>
说明:
<if>标签的test属性中写的是对象的属性名.
动态SQL之<choose>,<when>,<otherwise>
针对不想使用所有条件,而是想从多个条件中选择一个使用.<choose>有点像switch语句
<select id="findBlogLike" resultType="Blog">
select * from Blog where state = 'AVTIVE'
<choose>
<when test = "title != null">
AND title like #{title}
<when>
<when test ="title != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
动态SQL之<trim>,<where>,<set>
如果将上面where = 'ACTIVE',改写成where 1 = 1,可以使用<where>来简化开发
<select id="findBlogLike" resultType="Blog">
select * from Blog
<where>
<if test = "title != null">
AND title like #{title}
</if>
<if test ="title != null and autor.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
where元素只会在子元素返回任何内容的情况下才插入where子句,若开头为AND或者OR,where元素也会将他们自动省略.
trim可以用来定制where元素的功能
eg:
<trim prefix>="WHERE" prefixOverrides="AND | OR">
...
</trim>
prefixOverrides属性会忽略管道分隔符的文本序列,上面的例子会移除属性中指定的内容,并且插入prefix属性指定的内容.
set可以用于动态包含需要更新的列,忽略其他不更新的列
<update id="updateAuthor">
update Author
<set>
<if test = "username != null">username=#{username}</if>
<if test = "password != null">password=#{password}</if>
</set>
</update>
动态SQL之<foreach>
用于对集合进行遍历.
foreach元素的功能非常强大,他允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量.也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符.当集合为数组时index是当前迭代序号item值是获取的元素.
<!--在类QueryVo中加入一个list集合--->
<select id="selectPostIn" resultType="Post" parameterType"QueryVo">
select # from Post where ID in(1,2,3,4,5)
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>
补充:<include>
主要是用于sql语句的可重用,,并且可以接受参数来生成动态sql
<sql id="luck">
<sql>
<include refid="lick">
<property name="" value=""/>
</include>
文章参考mybatis文档.