mybatis 動態sql表達式相關應用

1、mybatis 表達式簡介git

  對於mybatis3 ,提供了一種動態sql的方式。經過動態sql咱們能夠直接在mybatis 的xm映射文件中直接經過條件判斷的方式進行查詢添加的拼接。mybatis 項目地址爲 http://github.com/mybatis/mybatis-3 。mybatis 3 提供以下條件判斷:github

  • if
  • choose (when, otherwise)
  • foreach

  if語句以下:sql

<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG 
  WHERE state = ‘ACTIVE’ 
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

  choose語句以下:數據庫

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>

  foreach語句以下mybatis

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

 2、相關技巧dom

  對於變量能夠使用#{param} 方式進行拼接。mybatis 也支持${param} 的方式。這兩種方式的區別以下:spa

  #{param}  表示讀取param參數的值,並將該值作字段的的值進行比較;code

  ${param} 表示讀取param的值,並將param值當成數據庫表中的某個字段。blog

  在數據量大的時候,咱們會使用維度表。將統計結果按期統計到維度表,展現的時候,直接讀取維度表的數據。it

  維度表結構以下:

DROP TABLE IF EXISTS `wd`;
CREATE TABLE `wd` (
  `id` varchar(64) NOT NULL,
  `xl` varchar(2) NOT NULL,
  `xzqh` varchar(2) NOT NULL,
  `nld` varchar(2) NOT NULL,
  `total` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

  統計的時候,須要根據xl(學歷),xzqh(行政區劃),nld(年齡段)進行分組查詢。sql以下:

select ${param}, sum(total)
from wd
group by ${param}

  parm 傳的值能夠是 「xl」、「xzqh」,「nld」 這樣經過一個sql就可完成這個功能。只須要傳遞不一樣的參數,從而完成對不一樣字段的分組統計。這中凡是在使用圖表的時候進行分組統計,能夠用的到。

相關文章
相關標籤/搜索