本文整理自网络,侵删。
1.MyBatis动态SQL
MyBatis 的强大特性之一便是它的动态 SQL,即拼接SQL字符串。如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。
通常使用动态 SQL 不可能是独立的一部分,MyBatis 当然使用一种强大的动态 SQL 语言来改进这种情形,这种语言可以被用在任意的 SQL 映射语句中。
动态 SQL 元素和使用 JSTL 或其他类似基于 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多的元素需要来了解。MyBatis 3 大大提升了它们,现在用不到原先一半的元素就可以了。MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。
2.动态SQL标签:if,choose (when, otherwise),trim (where, set),foreach
2.1 if标签:直接上代码
<select id="queryByIdAndTitle" resultType="Blog"> SELECT * FROM BLOG WHERE 1=1 <if test="id!= null and title!=null"> AND id=#{id} and title=#{title} </if> </select>
注:if标签一般用于非空验证,如上例,若id为空,if标签里的代码,将不会执行,反之,则会执行。
2.2 choose(when,otherwise)标签:直接上代码
<select id="queryBy" resultType="Blog"> SELECT * FROM BLOG WHERE 1=1 <choose> <when test="title != null"> AND title like #{title} </when> <otherwise> AND id= 1 </otherwise> </choose> </select>
注:choose(when,otherwise)标签相当于switch(case,default) ,如上例,若title 为空,when标签里的代码,将不会执行,默认执行otherwise标签里面的代码。
2.3 trim(where,set)标签:直接上代码
<select id="queryBy" resultType="com.scme.pojo.User" parameterType="com.scme.pojo.User"> select * from user <where> <if test="username!=null and password!=null"> and username=#{username} and password=#{password} </if> </where> </select>
注:假设上例传入的username,password不为空,代码就可以运行成功!但朋友们可能有疑问了,实际上执行的sql语句是什么呢?其实,sql为:select * from user
where username=? and password=? 朋友们是否发现,where标签代替了sql中where关键字,但if中的and不见了。其实where标签可以自动去除是“AND”或“OR”开头的sql中的“AND”或“OR”关键字。
如果 where 元素没有按正常套路出牌,我们还是可以通过自定义 trim 元素来定制sql,实现where标签的效果。代码如下:
<select id="queryBy" resultType="com.scme.pojo.User" parameterType="com.scme.pojo.User"> select * from user <trim prefix="WHERE" prefixOverrides="AND |OR "> <if test="username!=null and password!=null"> and username=#{username} and password=#{password} </if> </trim> <!-- 效果同上 <where> <if test="username!=null and password!=null"> and username=#{username} and password=#{password} </if> </where> --> </select>
set标签,代码如下:
<update id="updateUser" parameterType="com.scme.pojo.User"> update user <set> <if test="username!=null"> username=#{username} </if> </set> <where> <if test="id!=null"> id=#{id} </if> </where> </update>
注:set标签功能和where标签差不多,set标签代替了sql中set关键字,set标签可以自动去除sql中的多余的“,”
相关阅读 >>
用sql语句添加删除修改字段、一些表与字段的基本操作、数据库备份等
更多相关阅读请进入《sql》频道 >>
数据库系统概念 第6版
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。