读书人

MyBatis施用心得(3)

发布时间: 2012-10-14 14:55:08 作者: rapoo

MyBatis运用心得(3)
2.Dynamic SQL
动态sql是MyBaits的优点之一,在以往的IBatis就有动态sql,在此只是简要概述
在MyBatis中,sql的定义基于2中方式,一种是传统的XML文件,一种是Java的Mapper类生成
1)基于Mapper的动态SQL:
此部分在"MyBatis运用心得(2)"中已经叙述,主要是利用SelectBuilder和SqlBuilder,还是十分容易理解的。

2)基于XML文件的动态SQL:
主要是利用一些标签:<if>,<where>,<when>,<choose>,<otherwise>,<set>,<trim>,<foreach>
这些标签有一些与jstl比较相近,如<when>,<choose>,<otherwise>,<if>,<foreach>等。
<where>的作用主要是在一个where语句中如果有多个<if>,有可能会多出and和or连接符,如:

where<if test="name != null">    name = #{name}</if><if test="id != null">    and id = #{id}</if>

当name为null,id不为null时,sql为where and id = ?,出现错误。写成
<where>    <if test="name != null">        name = #{name}    </if>    <if test="id != null">        and id = #{id}    </if></where>

如果where后面第一个字符串时and或or,将会跳过

<set>的意思和where差不多,是实现update功能时一次set多个域
update A<set>    <if test="name != null">        name = #{name},    </if>    <if test="id != null">        id= #{id}    </if></set>


在此需要说明的是<if>,<when>标签只能做一些基本的条件判断,如"=",">","<",但如果要进行复杂条件判断,比如调用一个Java对象的方法,则显得力不从心,如果是基于Mapper的sql实现,SelectBuilder可以做的很好,但如果基于XML,就要求助于强大的表达式工具:ognl
比如现有一个OgnlHelper类,其中有一个判断是否有特殊字符的static方法hasSpecialChar,则可以通过ognl表示给出
<where>    <choose>        <when test="@com.test.OgnlHelper@hasSpecialChar(name)">            and name like '%'||#{name}||'%' escape '\'        </when>        <otherwise>            and name like '%'||#{name}||'%'        </otherwise>    </choose></where>

读书人网 >软件架构设计

热点推荐