先简单说下Mybatis的动态sql,这不是今天的重点。
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑。
例如,sql语句where条件中,需要一些安全判断,例如按某一条件查询时如果传入的参数是空,此时查询出的结果很可能是空的,也许我们需要参数为空时,是查出全部的信息
MyBatis中用于实现动态SQL的元素主要有:
- if
- choose(when,otherwise)
- trim
- where
- set
- foreach
示例mapper.xml:
<select id="findActiveBlogLike"
parameterType="BLOG" resultType="BLOG">
SELECT * FROM BLOG
WHERE
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND title like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</trim>
</select>
<update id="updateAuthorIfNecessary"
parameterType="Author">
update Author
<trim prefix="where" prefixOverrides=",">
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email}</if>
</set>
where id=#{id}
</trim>
</u