MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
虽然在以前使用动态 SQL 并非一件易事,但正是 MyBatis 提供了可以被用在任意 SQL 映射语句中的强大的动态 SQL 语言得以改进这种情形。
动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
- if/where
- choose(when,otherwise)
- trim(where,set)
- foreach
if/where
<select id = "find">
select * from user
<where>
<if test = "name != null and name != '' ">
and name like #{name}
</if>
</where>
</select>
choose when otherwise
当有name的时候就查name当有password的时候就查password
如果都没有就全查
<select id = "find">
select * from user
<where>
<choose>
<when test="name != null and name != '' ">
and name like #{name}
</when>
<when test = "passworid != null and password != '' ">
and password like #{password}
</when>
<otherwise>
and featured = 1
</otherwise>
</choose>
</where>
</select>
trim(自定义where条件) where set
//自定义where条件
<trim prefix = "where" prefixOverrides="AND | OR">
...
</trim>
//set的使用
<update id = "update">
update user
<set>
<if test = "username != null">username = #{username}, </if>
<if test = "password != null">password = #{password } </if>
</set>
where id = #{id}
</update>
foreach
<select id ="find">
select * from user where id in
<foreach item = "id" index = "index" collection="list" open="( separator="," colse=")">
#{id}
</foreach>
</select>