MyBatis运用心得(3)

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

[b]2)基于XML文件的动态SQL:[/b]
主要是利用一些标签:<if>,<where>,<when>,<choose>,<otherwise>,<set>,<trim>,<foreach>
这些标签有一些与jstl比较相近,如<when>,<choose>,<otherwise>,<if>,<foreach>等。
[b]<where>[/b]的作用主要是在一个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,将会跳过

[b]<set>[/b]的意思和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,就要求助于强大的表达式工具:[b]ognl[/b]
比如现有一个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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值