Mybatis的主要动态SQL有如下分类:
ps:网上有一篇写的很传神的blog ,估计用不上,先记录以下吧
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
if:有条件的包含where子句的一部分;比如:
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
choose、when、otherwise,栗子如下:
<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>
where:栗子如下:
<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>
要注意的是,此处的where不是查询语句中的where,而是<where></where>;
trim和where有点相似,只是使用规则稍微麻烦点;
trim 属性
prefix:前缀覆盖并增加其内容
suffix:后缀覆盖并增加其内容
prefixOverrides:前缀判断的条件
suffixOverrides:后缀判断的条件
suffix针对符合suffixOverrides的SQL语句追加后缀suffix值;prefix是针对符合preffixOverrides的语句添加前缀suffix值;
set,可以被用于包含需要更细的列,而舍弃其他的列。栗子:
<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>
foreach
功能:向sql传递数组或是list;
参数、属性:
collection,指定输入对象中的集合属性;
item,表示集合中每一个元素进行迭代时的别名;
index,指定一个名字,表示在迭代过程中,每次迭代到的位置;
open,表示该语句什么时候开始;
separator,表示每次迭代过程中以什么符号分割;
close,表示以什么结束;
重点说一下collection属性,当传入的参数是一个list的时候,其属性是list;如果传入参数是一个array数组的时候,其属性是array;
如果传入的参数是多个的时候,需要封装成一个map。
<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>
bind可以从OGNL表达式中创建一个变量并将其绑定到上下文:
<select id="findByNameStr4" resultMap="userMap">
<bind name="abc" value="'%' + _parameter + '%'" />
select * from users where name like #{abc}
</select>