MyBatis的动态SQL

MyBatis中的动态sql

(1) MyBatis 的强大特性之一便是它的动态 SQL。如果有使用JDBC或其他类似框架的经验,就能体会到根据不同条件拼接SQL语句的痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态SQL这一特性可以彻底摆脱这种痛苦;

(2) 动态 SQL 元素和使用JSTL或其他类似基于 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要来了解。MyBatis 3大大提升了它们,现在用不到原先一半的元素就可以实现相同的功能;

(3) MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素;

一. 动态SQL通常要做的事情是有条件地包含where子句的一部分。如:

<select id="findPersonWithNameLike" resultType="Person">

  select * from person where 1=1

  <if test="_parameter!=null and _parameter!=''">

  and name like #{name}

  </if>

</select>

二.  有些时候,不想用到所有的条件语句,而只想从中择其一二。针对这种情况,MyBatis提供了choose元素,它有点像Java中的switch语句: 

条件不定的模糊查询为了解决在查询后添加and还是where的情况,通常利用一个必定为真的条件先给出where子句,后续条件则直接追加and即可

choose类似switch,when节点则类似case,otherwise(可选)节点则和default语句的功能类似

<select id="findPersonWithChooseLike" resultType="Person">

select * from person where 1=1

<choose>

<when test="name!=null and name!=''">

and name like #{name}

</when>

<when test="age>0">

and age &lt; #{age}

</when>

<otherwise>

and address like #{address}

</otherwise>

</choose>

</select>

 三.  在之前的示例中,使用了1=1这种明确为true的条件来解决应该插入where还是插入and|or的问题,而新版本的MyBatis提供了新标签(where、trim)来使用更优雅的方式来解决这个问题:

where 元素知道只有在一个以上的if条件有值的情况下才去插入“WHERE”子句。而且,若最后的内容是“AND”或“OR”开头的,where 元素也知道如何将他们替换

<select id="findPersonWithNameLike" resultType="Person">

select * from person

<where>

<if test="name!=null and name!=''">

name like #{name}

</if>

<if test="address!=null and address!=''">

and address like #{address}

</if>

</where>

</select>

四. 如果where元素失效,还可以通过自定义trim元素来定制想要的功能。比如,和上例where元素等价的自定义trim元素为:

 

<select id="findPersonWithWhereLike" resultType="Person">

select * from person

<trim prefix="where" prefixOverrides="AND|OR">

<if test="name!=null and name!=''">

name like #{name}

</if>

<if test="address!=null and address!=''">

and address like #{address}

</if>

</trim>

</select> 

五. 类似的用于动态更新语句的解决方案叫做set。set 元素可以被用于动态包含需要更新的列,而舍去其他的。如:

和where元素类似,set节点也会自动在SQL语句中加入set子句,并且在合适的时候会自动删除末尾多余的逗号

<update id="updatePersonById" parameterType="Person">

update person

<set>

<if test="name!=null and name!=''">

name = #{name},

</if>

<if test="address!=null and address!=''">

address = #{address}

</if>

</set>

where id=#{id}

</update> 

六. 也能使用等价的自定义trim元素完成同等功能,结果如下图: 

suffixOverrides="," 忽略的是后缀中的值(逗号),而又一次附加了前缀中的值(SET)

<update id="updatePersonById" parameterType="Person">

update person

<trim prefix="set" suffixOverrides=",">

<if test="name!=null and name!=''">

name = #{name},

</if>

<if test="address!=null and address!=''">

address = #{address}

</if>

</trim>

where id=#{id}

</update> 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值