动态sql叙述
MyBatis 的一个强大的特性之一通常是它的动态 SQL 能力。 如果你有使用 JDBC 或其他 相似框架的经验,你就明白条件地串联 SQL 字符串在一起是多么的痛苦,确保不能忘了空 格或在列表的最后省略逗号。动态 SQL 可以彻底处理这种痛苦。
通常使用动态 SQL 不可能是独立的一部分,MyBatis 当然使用一种强大的动态SQL语言来改进这种情形,这种语言可以被用在任意映射的 SQL 语句中。
动态 SQL 元素和使用 JSTL 或其他相似的基于 XML 的文本处理器相似。在 MyBatis 之 前的版本中,有很多的元素需要来了解。MyBatis 3 大大提升了它们,现在用不到原先一半 的元素就能工作了。MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。
• if
• choose (when, otherwise)
• trim (where, set)
• foreach
If标签
If:是一个条件,如果条件成立,则把if中的SQL指令拼接到外部的SQL指令中。在接口上添加了一个查询的方法.
<select id="search" parameterType="map" resultMap="userMap">
select * from smbms_user u inner join
smbms_role r on u.userRole = r.id where 1=1
<if test="userName!=null">
and u.userName like #{userName}
</if>
<if test="userRole!=null">
and u.userRole=#{userRole}
</if>
上面where后面的1=1是为了解决当第一个条件不带and时并且第一个条件不成立出现的where and …的类似错误,这样虽然可以解决问题但是不符合sql的编写规范,下面的这个标签可以避免这种问题
where标签
Where: 它可以自动为SQL指令添加where 关键字,并且会把条件里面多余的and 关键字去掉。如果没有任何条件成立,则where关键字也不会添加。
<select id="search" parameterType="map" resultMap="userMap">
select * from smbms_user u inner join
smbms_role r on u.userRole = r.id
<where>
<if test="userName!=null">
and u.userName like #{userName}
</if>
<if test="userRole!=null">
and u.userRole=#{userRole}
</if>
</where>
</select>
看这样是不是很香,再也不用担心and的问题了
set标签
Set:是用于Update语句中,它可以自动加上Set关键字,并且去掉多余的逗号,通常是最后一个(,)。
来看下面一组对比:
<update id="modify" parameterType="User">
<!-- 原来的修改SQL语句,替换成了动态SQL
update smbms_user set userName=#{userName},
gender=#{gender},birthday=#{birthday},phone=#{phone},
address=#{address},userRole=#{user.id},modifyBy=#{modifyBy},
modifyDate=#{modifyDate} where id = #{id} -->
<!--这里使用了动态sql来处理更新-->
update smbms_user
<set>
<if test="userName!=null">
userName=#{userName},
</if>
<if test="gender!=null">
gender=#{gender},
</if>
<if test="birthday!=null">
birthday=#{birthday},
</if>
<if test="phone!=null">
phone=#{phone},
</if>
<if test="address!=null">
address=#{address},
</if>
<if test="userRole!=null">
userRole=#{user.id},
</if>
<if test="modifyBy!=null">
modifyBy=#{modifyBy},
</if>
<if test="modifyDate!=null">
modifyDate=#{modifyDate},
</if>
</set>
where id = #{id}
</update>
像上面这样就可以方便对有用的数据进行更新操作,减轻了数据库的负担
foreach
foreach:对数据进行遍历,迭代。在MyBites中通常用于in关键字中。比如我们实现多选删除的功能时,把多个主键值封装成list集合中,传递到映射文件中。
<delete id="deleteAll" parameterType="list">
delete from smbms_user where id in
<foreach collection="list" open="(" close=")"
separator="," item="i">
#{i}
</foreach>
</delete>
choose(when、otherwise) 这是一个多重if,如果when 只有一个,则就是一个if else 语句。
open为开始的 ( 左括号,close为结束的 ) 右括号,separator为循环时指定i的分割符 ’ , ’ 逗号
以上就是我对动态sql的一些整理,希望大家采纳