-
mybatis 动态sql简介
MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。 -
if 语句 (简单的条件判断)
-
choose(when,otherwise),相当于JAVA语言中的switch,与jstl中的choose很类似。
-
trim1(对包含的内容加上prefix,或者suffix等,前缀,后缀)
-
where(主要是用来简化sql语句中where条件判断的,能智能处理 and or ,不用担心多余导致语法错误)
-
set (主要用于跟新)
-
foreach (在实现mybatis in 语法查询时特别有用)
2 .分支判断
- if 元素
根据 username 和 sex 来查询数据。如果username为空,那么将只根据sex来查询;反之只根据username来查询
首先不使用 动态SQL 来书写
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="User">
select * from user where username=#{username} and sex=#{sex}
</select>
上面的查询语句,我们可以发现,如果 #{username} 为空,那么查询结果也是空,如何解决这个问题呢?使用 if 来判断
<select id="selectUserByUsernameAndSex" resultType="user"
parameterType="User">
select * from user where
<if test="username != null">
username=#{username}
</if>
<if test="sex!= null">
and sex=#{sex}
</if>
</select>
这样写我们可以看到,如果 sex 等于 null,那么查询语句为 select * from user where username=#{username},但是如果usename 为空呢?那么查询语句为 select * from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句
- 动态SQL:if+where 语句
<select id="selectUserByUsernameAndSex" resultType="User" parameterType="User">
<where>
<if test="username != null">
username=#{username}
</if>
<if test="sex != null">
and sex=#{sex}
</if>
</where>
</select>
这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会自动去掉多余的and 或者or。
4. 动态SQL:if+set 语句
同理,上面的对于查询 SQL 语句包含 where 关键字,如果在进行更新操作的时候,含有 set 关键词,我们怎么处理呢?
<!-- 根据 id 更新 user 表的数据 -->
<update id="updateUserById" parameterType="User">
update user u
<set>
<if test="username != null and username != ''">
u.username = #{username},
</if>
<if test="sex != null and sex != ''">
u.sex = #{sex},
</if>
</set>
where id=#{id}
</update>
其余不常用,了解即可。