mybatis 动态sql表达式相关应用

一、mybatis 表达式简介

  对于mybatis3 ,提供了一种动态sql的方式。通过动态sql我们可以直接在mybatis 的xm映射文件中直接通过条件判断的方式进行查询添加的拼接。mybatis 项目地址为 http://github.com/mybatis/mybatis-3 。mybatis 3 提供如下条件判断:

  • if
  • choose (when, otherwise)
  • foreach

  if语句如下:

<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语句如下

<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>

 二、相关技巧

  对于变量可以使用#{param} 方式进行拼接。mybatis 也支持${param} 的方式。这两种方式的区别如下:

  #{param}  表示读取param参数的值,并将该值做字段的的值进行比较;

  ${param} 表示读取param的值,并将param值当成数据库表中的某个字段。

  在数据量大的时候,我们会使用维度表。将统计结果定期统计到维度表,展示的时候,直接读取维度表的数据。

  维度表结构如下:

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就可完成这个功能。只需要传递不同的参数,从而完成对不同字段的分组统计。这中凡是在使用图表的时候进行分组统计,可以用的到。

原文地址:https://www.cnblogs.com/always-online/p/5342510.html