好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

第三章 MyBatis框架动态SQL

动态SQL语句是基于 OGNL 表达式的 通过动态SQL完成多条件查询等逻辑实现 用于实现动态SQL的元素主要有

标签 说明 if 条件判断 where 为SQL语句动态添加where关键字 choose 条件判断 foreach 以遍历方式处理集合类型参数 set 为SQL语句动态添加set关键字,实现动态实现数据更新功能 trim 为SQL语句进行格式化处理,添加或移除后缀

 

if

使用进行条件判断

where

简化SQL语句中where条件判断

智能处理and和or

  < select  id= "count"  resultType= "int"  parameterType= "map" >
      select count(1) from t_sys_user
      < where >
          < if test= "account != null" > <!--test条件判断 返回true或false-->
              and account like concat(‘%‘,#{account},‘%‘)
          </ if >
          < if test= "roleId != null and roleId !=-1" >
              and roleId=#{roleId}
          </ if >
      </ where >
    </ select >

Choose标签 先判断 when的test中的条件为true 就不走下面的版块,直接跳出Choose标签 choose(when、otherwise) 相当于Java中switch语句 当when有条件满足的时候,就跳出choose

  < choose >
              < when test= "" ></ when >
              < when test= "" ></ when >
              < otherwise ></ otherwise >
</ choose >

foreach标签

参数为List参数

   < foreach  collection= "list"  item= "item"  open= "("  separator= ","  close= ")" >
          #{item}
        </ foreach >

参数为数组

   < foreach  collection= "array"  item= "item"  open= "("  separator= ","  close= ")" >
          #{item}
        </ foreach >

参数为Map类型

  < foreach  collection= "roleList"  item= "item"  open= "("  separator= ","  close= ")" >
          #{item}
        </ foreach >
属性 介绍 item 遍历数组时,为数组或List集合起的别名 open 起始位置的拼接字符 表示in 语句"(" close 结束位置的拼接字符 表示in 语句")" separator 连接字符比如, collection 参数为array时是数组,参数是为list时是list集合,参数为map类型指定的key值( 必写 ) index 当前元素位置下标

set标签

与where相似,添加一个set关键字

若某个参数为null,则不需要更新,保持数据库原值

  < set ></ set >      

trim标签

能够动态添加前缀,并可以智能地忽略标签前后多余的and、or 或,

  < trim  prefix= "前缀"  suffix= "后缀"  prefixOverrides= "忽略前缀"  suffixOverrides= "忽略后缀" >
           
</ trim >

trim标签

属性 介绍 prefix 前缀 suffix 后缀 prefixOverrides 忽略前缀 suffixOverrides 忽略后缀

能更灵活地去除多余关键字替代where和set

 

第三章 MyBatis框架动态SQL

标签:框架   更新   contain   col   新功能   racket   otherwise   expand   属性   

查看更多关于第三章 MyBatis框架动态SQL的详细内容...

  阅读:23次