MyBatis的sql元素

MyBatis的sql元素

与strus2相比而言,myBatis独特于支持可手动编写符合需求的sql语句,并且myBatis结合了Ognl表达式帮助实现sql语句。
mybatis的几种动态sql元素:

  1. If
  2. choose
  3. trim,where.,set
  4. foreach

1.If:像平常的查询语句,用if来判断是否有值传入,

 <select id="getBooks"  resultType="map" >
   select <include refid="Base_Column_List"/>
   from t_book
   where 1=1
   <if test="bookName != null">
    and book_name like CONCAT(CONCAT('%',#{bookName}),'%')
   </if>

  </select>

2.choose:当书名不为空时,拼接语句,当简介不为空时,拼接下调语句,像这样只是拿几个值来做选择适合用到choose,

<select id="list" resultMap="row" resultType="java.util.List">
    select
    <include refid="Base_Column_List" />
    from t_book
    where 1=1
    <choose>
      <when test="bookName != null">
        and book_name like CONCAT(CONCAT('%',#{bookName,jdbcType=VARCHAR}),'%')
      </when>
      <when test="bookBrief != null">
        and book_brief like CONCAT(CONCAT('%',#{bookBrief,jdbcType=VARCHAR}),'%')
      </when>
      <otherwise ></otherwise>
    </choose>
  </select>

当这两者都为空时,可最后使用:

<otherwise></otherise>。

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

<select id="findActiveBlogLike"   resultType="Blog">
  select * from  t_book
  <where> 
    <if test="state != null">
         state = #{state}
    </if> 
    <if test="title != null">
        andtitle like #{title}
    </if>
    <if test="author != null and author.name != null">
        andauthor_name like #{author.name}
    </if>
  </where>
</select>

trim:如果 where 元素没有按正常套路出牌,我们还是可以通过自定义 trim 元素来定制我们想要的功能。比如,和 where 元素等价的自定义 trim 元素为:

<trim prefix="where" prefixOverrides="and |or ">
  ... 
</trim>

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

<update id="updateByPrimaryKeySelective" parameterType="com.zking.ssm.model.Book" >
    update t_book
    <set >
      <if test="bookName != null" >
        book_name = #{bookName,jdbcType=VARCHAR},
      </if>
      <if test="bookPrice != null" >
        book_price = #{bookPrice,jdbcType=REAL},
      </if>
      <if test="bookBrief != null" >
        book_brief = #{bookBrief,jdbcType=VARCHAR},
      </if>
    </set>
    where book_id = #{bookId,jdbcType=INTEGER}
  </update>

4:foreach:动态 SQL 的另外一个常用的必要操作是需要对一个集合进行遍历,通常是在构建 in条件语句的时候。比如:

<select id="selectPostIn" resultType="domain.blog.Post">
  select * form t_book
  where book_id in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值