动态 sql
mybatis 的强大特性之一便是它的动态 sql。如果你有使用 jdbc 或其他类似框架的经验,你就能体会到根据不同条件拼接 sql 语句有多么痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉一连串列名最后的逗号。利用动态 sql 这一特性可以彻底摆脱这种痛苦。
通常使用动态 sql 不可能是独立的一部分,mybatis 通过一种强大的动态 sql 语言明显地改进了这种情形,这种语言可以被用在任意的 sql 映射语句中。
<code>if choose (when, otherwise) trim (where, set) foreach</code>
if
动态 sql 通常要做的事情是有条件地包含 where 子句的一部分。比如:
<code><select id="findactiveblogwithtitlelike" resulttype="blog"> select * from blog where state = ‘active’ <if test="title != null"> and title like #{title} </if> </select></code>
这条语句提供了一个可选的文本查找类型的功能。如果没有传入“title”,那么所有处于“active”状态的blog都会返回;反之若传入了“title”,则会模糊查找“title”内容的blog来返回(就这个例子而言,细心的读者会发现其中的参数值是可以包含一些掩码或通配符的)。
如果想让“title”和“author”两个条件进行可选搜索呢?首先,改变语句的名称让它更具实际意义;然后只要加入另一个条件即可。
<code><select id="findactivebloglike" resulttype="blog"> select * from blog where state = ‘active’ <if test="title != null"> and title like #{title} </if> <if test="author != null and author.name != null"> and author_name like #{author.name} </if> </select></code>
choose, when, otherwise
有些时候,我们不想用到所有的条件语句,而只想从中择其一二。针对这种情况,mybatis 提供了 choose 元素,它有点像 java 中的 switch 语句。
还是上面的例子,但是这次变为提供了“title”就按“title”查找,提供了“author”就按“author”查找,若两者都没有提供,就返回所有符合条件的blog(实际情况可能是由管理员按一定策略选出blog列表,而不是返回大量无意义的随机结果)。
<code><select id="findactivebloglike" resulttype="blog"> select * from blog where state = ‘active’ <choose> <when test="title != null"> and title like #{title} </when> <when test="author != null and author.name != null"> and author_name like #{author.name} </when> <otherwise> and featured = 1 </otherwise> </choose> </select></code>
trim, where, set
前面的例子已经合宜地解决了一个臭名昭著的动态 sql 问题。现在考虑回到“if”示例,但这次我们将“active = 1”也设置成一个动态条件,将会发生什么情况。
<code><select id="findactivebloglike" resulttype="blog"> select * from blog where <if test="state != null"> state = #{state} </if> <if test="title != null"> and title like #{title} </if> <if test="author != null and author.name != null"> and author_name like #{author.name} </if> </select></code>
如果这些条件没有一个能匹配上将会怎样?最终这条 sql 会变成这样:
<code>select * from blog where</code>
这会导致查询失败。如果仅仅第二个条件匹配又会怎样?这条 sql 最终会是这样:
<code>select * from blog where and title like ‘sometitle’</code>
这个查询也会失败。这个问题不能简单的用条件句式来解决,如果你也曾经被迫这样写过,那么你很可能从此以后都不想再这样去写了。
mybatis 有一个简单的方案,在90%的情况下都会生效。同时你可以用自定义方式来处理不生效的情况。只需简单的更改,一切即可正常运行:
<code><select id="findactivebloglike" resulttype="blog"> select * from blog <where> <if test="state != null"> state = #{state} </if> <if test="title != null"> and title like #{title} </if> <if test="author != null and author.name != null"> and author_name like #{author.name} </if> </where> </select></code>
where 元素只在至少一个 if条件符合的情况下才去插入“where”子句。而且,如果内容是“and”或“or”开头的,where 元素便会将他们去除。
如果 where 元素没有按你想的准确执行,你还可以通过自定义 trim 元素来定制你想要的功能。比如,和 where 元素等价的trim 元素为:
<code><trim prefix="where" prefixoverrides="and |or "> ... </trim></code>
prefixoverrides 属性会忽略通过管道分隔的文本序列(注意此例中的空格也是必要的)。即移除 prefixoverrides 属性中指定的内容,同时插入 prefix 属性中的所有内容。
类似的用于动态更新语句的解决方案叫做 set。set 元素可以被用于动态包含需要更新的列,而省略其他的。比如:
<code><update id="updateauthorifnecessary"> update author <set> <if test="username != null">username=#{username},</if> <if test="password != null">password=#{password},</if> <if test="email != null">email=#{email},</if> <if test="bio != null">bio=#{bio}</if> </set> where id=#{id} </update></code>
这里,set 元素会动态前置 set 关键字,同时也会消除额外的逗号,因为用了条件语句之后很可能就会在生成的赋值语句的后面留下这些逗号。
若你对等价的自定义 trim 元素的样子感兴趣,这就是:
<code><trim prefix="set" suffixoverrides=","> ... </trim></code>
注意这里我们忽略的是后缀中的值,而又一次附加了前缀中的值。
foreach
动态 sql 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 in 条件语句的时候。比如:
<code><select id="selectpostin" resulttype="domain.blog.post"> select * from post p where id in <foreach item="item" index="index" collection="list" open="(" separator="," close=")"> #{item} </foreach> </select></code>
foreach 元素的功能是非常强大的,它允许你指定一个集合,声明可以用在元素体内的集合项和索引变量。它也允许你指定开闭匹配的字符串以及在迭代中间放置分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。
注意 你可以将任何可迭代对象(如列表、集合等)和任何的字典或者数组对象传递给foreach作为集合参数。当使用可迭代对象或者数组时,index是当前迭代的次数,item的值是本次迭代获取的元素。当使用字典(或者map.entry对象的集合)时,index是键,item是值。
到此我们已经完成了涉及 xml 配置文件和 xml 映射文件的讨论。下一部分将详细探讨 java api,这样才能从已创建的映射中获取最大利益。
bind
bind 元素可以从 ognl 表达式中创建一个变量并将其绑定到上下文。比如:
<code><select id="selectblogslike" resulttype="blog"> <bind name="pattern" value="'%' + _parameter.gettitle() + '%'" /> select * from blog where title like #{pattern} </select> multi-db vendor support</code>
一个配置了“_databaseid”变量的 databaseidprovider 对于动态代码来说是可用的,这样就可以根据不同的数据库厂商构建特定的语句。比如下面的例子:
<code><insert id="insert"> <selectkey keyproperty="id" resulttype="int" order="before"> <if test="_databaseid == 'oracle'"> select seq_users.nextval from dual </if> <if test="_databaseid == 'db2'"> select nextval for seq_users from sysibm.sysdummy1" </if> </selectkey> insert into users values (#{id}, #{name}) </insert></code>
动态 sql 中可插拔的脚本语言
mybatis 从 3.2 开始支持可插拔的脚本语言,因此你可以在插入一种语言的驱动(language driver)之后来写基于这种语言的动态 sql 查询。
可以通过实现下面接口的方式来插入一种语言:
<code>public interface languagedriver { parameterhandler createparameterhandler(mappedstatement mappedstatement, object parameterobject, boundsql boundsql); sqlsource createsqlsource(configuration configuration, xnode script, class<?> parametertype); sqlsource createsqlsource(configuration configuration, string script, class<?> parametertype); }</code>
一旦有了自定义的语言驱动,你就可以在 mybatis-config.xml 文件中将它设置为默认语言:
<code><typealiases> <typealias type="org.sample.mylanguagedriver" alias="mylanguage"/> </typealiases> <settings> <setting name="defaultscriptinglanguage" value="mylanguage"/> </settings></code>
除了设置默认语言,你也可以针对特殊的语句指定特定语言,这可以通过如下的 lang 属性来完成:
<code><select id="selectblog" lang="mylanguage"> select * from blog </select></code>
或者在你正在使用的映射中加上注解 @lang 来完成:
<code>public interface mapper { @lang(mylanguagedriver.class) @select("select * from blog") list<blog> selectblog(); }</code>
注意 可以将 apache velocity 作为动态语言来使用,更多细节请参考 mybatis-velocity 项目。
你前面看到的所有 xml 标签都是默认 mybatis 语言提供的,它是由别名为 xml 语言驱动器 org.apache.ibatis.scripting.xmltags.xmllanguagedriver 驱动的。