Mybatis 文档篇 6:SQL Builder Class

1 问题

One of the nastiest things a Java developer will ever have to do is embed SQL in Java code. Usually this is done because the SQL has to be dynamically generated - otherwise you could externalize it in a file or a stored proc. As you've already seen, MyBatis has a powerful answer for dynamic SQL generation in its XML mapping features. However, sometimes it becomes necessary to build a SQL statement string inside of Java code. In that case, MyBatis has one more feature to help you out, before reducing yourself to the typical mess of plus signs, quotes, newlines, formatting problems and nested conditionals to deal with extra commas or AND conjunctions. Indeed, dynamically generating SQL code in Java can be a real nightmare. For example:
Java 程序员最痛苦的事情之一是不得不在 Java 代码中嵌入 SQL 语句。通常这样做是因为 SQL 语句必须动态生成——不然你要将其放在外部文件中或一个存储过程中。正如你所看到的,MyBatis 对于在其 XML 映射特性中动态生成 SQL 有一个强大的解决方案。然而,有时候在 Java 代码中构建一个 SQL 语句的字符串是必要的。在这种情况下,Mybatis 有另外一个特性可以帮助你,在你陷入典型的加号、引号、新行、格式化问题和嵌入条件时处理多余的逗号和 AND 连接之前。事实上,动态地在 Java 中生成 SQL 代码就像一场噩梦。例如:

String sql = "SELECT P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME, "
"P.LAST_NAME,P.CREATED_ON, P.UPDATED_ON " +
"FROM PERSON P, ACCOUNT A " +
"INNER JOIN DEPARTMENT D on D.ID = P.DEPARTMENT_ID " +
"INNER JOIN COMPANY C on D.COMPANY_ID = C.ID " +
"WHERE (P.ID = A.ID AND P.FIRST_NAME like ?) " +
"OR (P.LAST_NAME like ?) " +
"GROUP BY P.ID " +
"HAVING (P.LAST_NAME like ?) " +
"OR (P.FIRST_NAME like ?) " +
"ORDER BY P.ID, P.FULL_NAME";

2 解决方案

MyBatis 3 offers a convenient utility class to help with the problem. With the SQL class, you simply create an instance that lets you call methods against it to build a SQL statement one step at a time. The example problem above would look like this when rewritten with the SQL class:
MyBatis 3 提供了一个方便的工具类可以帮助你处理这个问题。使用 SQL 类,你只要简单地创建一个实例,通过它可以调用方法来一步一步地构建 SQL 语句。上面示例中的问题在使用 SQL 类重写后会变成这个样子:

private String selectPersonSql() {
  return new SQL() {{
    SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
    SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
    FROM("PERSON P");
    FROM("ACCOUNT A");
    INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID");
    INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID");
    WHERE("P.ID = A.ID");
    WHERE("P.FIRST_NAME like ?");
    OR();
    WHERE("P.LAST_NAME like ?");
    GROUP_BY("P.ID");
    HAVING("P.LAST_NAME like ?");
    OR();
    HAVING("P.FIRST_NAME like ?");
    ORDER_BY("P.ID");
    ORDER_BY("P.FULL_NAME");
  }}.toString();
}

What is so special about that example? Well, if you look closely, it doesn't have to worry about accidentally duplicating "AND" keywords, or choosing between "WHERE" and "AND" or none at all. The SQL class takes care of understanding where "WHERE" needs to go, where an "AND" should be used and all of the String concatenation.
这个例子有何特殊之处呢?如果你仔细观察,你会发现你不用再担心不小心多写了个 “AND” 关键字,或在 "WHERE" 和 "AND" 之间做选择还是两者都不选。SQL 类会非常注意 "WHERE" 应该出现在哪里,哪里 "AND" 需要使用,以及所有的字符串连接。

3 SQL 类

我们先来看看例子:

// 匿名内部类
public String deletePersonSql() {
  return new SQL() {{
    DELETE_FROM("PERSON");
    WHERE("ID = #{id}");
  }}.toString();
}

// Builder / Fluent 风格
public String insertPersonSql() {
  String sql = new SQL()
    .INSERT_INTO("PERSON")
    .VALUES("ID, FIRST_NAME", "#{id}, #{firstName}")
    .VALUES("LAST_NAME", "#{lastName}")
    .toString();
  return sql;
}

// 带条件 (注意参数被声明为 final,是匿名内部类访问它们所要求的)
public String selectPersonLike(final String id, final String firstName, final String lastName) {
  return new SQL() {{
    SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME");
    FROM("PERSON P");
    if (id != null) {
      WHERE("P.ID like #{id}");
    }
    if (firstName != null) {
      WHERE("P.FIRST_NAME like #{firstName}");
    }
    if (lastName != null) {
      WHERE("P.LAST_NAME like #{lastName}");
    }
    ORDER_BY("P.LAST_NAME");
  }}.toString();
}

public String deletePersonSql() {
  return new SQL() {{
    DELETE_FROM("PERSON");
    WHERE("ID = #{id}");
  }}.toString();
}

public String insertPersonSql() {
  return new SQL() {{
    INSERT_INTO("PERSON");
    VALUES("ID, FIRST_NAME", "#{id}, #{firstName}");
    VALUES("LAST_NAME", "#{lastName}");
  }}.toString();
}

public String updatePersonSql() {
  return new SQL() {{
    UPDATE("PERSON");
    SET("FIRST_NAME = #{firstName}");
    WHERE("ID = #{id}");
  }}.toString();
}

方法说明如下:

  • SELECT(String)
    SELECT(String...)

    Starts or appends to a SELECT clause. Can be called more than once, and parameters will be appended to the SELECT clause. The parameters are usually a comma separated list of columns and aliases, but can be anything acceptable to the driver.
    开始或拼接 SELECT 子句。可以多次调用,参数会拼接给 SELECT 子句。参数通常是一个逗号分隔的列或列别名的列表,但也可以是数据库驱动可以接受的任何类型。

  • SELECT_DISTINCT(String)
    SELECT_DISTINCT(String...)

    Starts or appends to a SELECT clause, also adds the DISTINCT keyword to the generated query. Can be called more than once, and parameters will be appended to the SELECT clause. The parameters are usually a comma separated list of columns and aliases, but can be anything acceptable to the driver.
    开始或拼接 SELECT 子句,并添加 DISTINCT 关键字到生成的查询语句中。可以多次调用,参数会拼接给 SELECT 子句。参数通常是一个逗号分隔的列或列别名的列表,但也可以是数据库驱动可以接受的任何类型。

  • FROM(String)
    FROM(String...)

    Starts or appends to a FROM clause. Can be called more than once, and parameters will be appended to the FROM clause. Parameters are usually a table name and an alias, or anything acceptable to the driver.
    开始或拼接 FROM 子句。可以多次调用,参数会拼接给 FROM 子句。参数通常是一个表名和一个别名,或者任何数据库驱动可以接受的类型。

  • JOIN(String)
    JOIN(String...)
    INNER_JOIN(String)
    INNER_JOIN(String...)
    LEFT_OUTER_JOIN(String)
    LEFT_OUTER_JOIN(String...)
    RIGHT_OUTER_JOIN(String)
    RIGHT_OUTER_JOIN(String...)

    Adds a new JOIN clause of the appropriate type, depending on the method called. The parameter can include a standard join consisting of the columns and the conditions to join on.
    根据方法调用添加一个新的合适类型的 JOIN 子句。参数可以包含一个由列和 join on 的条件组成的标准 join。

  • WHERE(String)
    WHERE(String...)

    Appends a new WHERE clause condition, concatenated byAND. Can be called multiple times, which causes it to concatenate the new conditions each time withAND. Use OR() to split with anOR.
    拼接一个新的 WHERE 条件子句,通过 AND 拼接。可以多次调用,每次都会由 AND 来拼接新的条件。使用 OR() 来分隔 OR。

  • OR()
    Splits the current WHERE clause conditions with anOR. Can be called more than once, but calling more than once in a row will generate erraticSQL.
    用 OR 来分隔当前的 WHERE 条件子句。可以多次调用,但是在一行中多次调用将生成不稳定的 SQL。

  • AND()
    Splits the current WHERE clause conditions with anAND. Can be called more than once, but calling more than once in a row will generate erraticSQL. Because WHERE and HAVING both automatically concatenate with AND, this is a very uncommon method to use and is only really included for completeness.
    用 AND 来分隔当前的 WHERE 条件子句。可以多次调用,但是在一行中多次调用将生成不稳定的 SQL。因为 WHERE 和 HAVING 都会用 AND 连接自动生成,这是不常用的方法只是基于完整性才被使用。

  • GROUP_BY(String)
    GROUP_BY(String...)

    Appends a new GROUP BY clause elements, concatenated by a comma. Can be called multiple times, which causes it to concatenate the new conditions each time with a comma.
    拼接一个新的 GROUP BY 子句元素,由逗号连接。可以被多次调用,每追加一个条件都会使用逗号来连接。

  • HAVING(String)
    HAVING(String...)

    Appends a new HAVING clause condition, concatenated by AND. Can be called multiple times, which causes it to concatenate the new conditions each time withAND. Use OR() to split with anOR.
    拼接一个新的 HAVING 条件子句,由 AND 连接。可以被多次调用,每追加一个条件都会使用 AND 来连接。使用 OR() 来分隔 OR。

  • ORDER_BY(String)
    ORDER_BY(String...)

    Appends a new ORDER BY clause elements, concatenated by a comma. Can be called multiple times, which causes it to concatenate the new conditions each time with a comma.
    拼接一个新的 ORDER BY 子句元素,由逗号连接。可以被多次调用,每追加一个条件都会使用逗号来连接。

  • DELETE_FROM(String)
    Starts a delete statement and specifies the table to delete from. Generally this should be followed by a WHERE statement!
    开始一个 delete 语句并指定要从中删除数据的表。通常它后面应该跟着一个 WHERE 语句。

  • INSERT_INTO(String)
    Starts an insert statement and specifies the table to insert into. This should be followed by one or more VALUES() or INTO_COLUMNS() and INTO_VALUES() calls.
    开始一个 insert 语句并指定要插入数据的表。它后面应该跟着一个或多个 VALUES() 或 INTO_COLUMNS() 和 INTO_VALUES() 调用。

  • SET(String)
    SET(String...)

    Appends to the "set" list for an update statement.
    为一个 update 语句拼接 "set" 列表。

  • UPDATE(String)
    Starts an update statement and specifies the table to update. This should be followed by one or more SET() calls, and usually a WHERE() call.
    开始一个 update 语句并指定要更新数据的表。它后面应该跟着一个或多个SET() 调用,通常还有一个 WHERE() 调用。

  • VALUES(String, String)
    Appends to an insert statement. The first parameter is the column(s) to insert, the second parameter is the value(s).
    拼接到一个 insert 语句。第一个参数是要插入的列,第二个参数是对应要插入的值。

  • INTO_COLUMNS(String...)
    Appends columns phrase to an insert statement. This should be call INTO_VALUES() with together.
    拼接列短语到一个 insert 语句。它应该跟 INTO_VALUES() 一起调用。

  • INTO_VALUES(String...)
    Appends values phrase to an insert statement. This should be call INTO_COLUMNS() with together.
    拼接值短语到一个 insert 语句。它应该跟 INTO_COLUMNS() 一起调用。

Since version 3.4.2, you can use variable-length arguments as follows:
从 3.4.2 版本开始,你可以使用像下面这样使用 variable-length 参数。

public String selectPersonSql() {
  return new SQL()
    .SELECT("P.ID", "A.USERNAME", "A.PASSWORD", "P.FULL_NAME", "D.DEPARTMENT_NAME", "C.COMPANY_NAME")
    .FROM("PERSON P", "ACCOUNT A")
    .INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID", "COMPANY C on D.COMPANY_ID = C.ID")
    .WHERE("P.ID = A.ID", "P.FULL_NAME like #{name}")
    .ORDER_BY("P.ID", "P.FULL_NAME")
    .toString();
}

public String insertPersonSql() {
  return new SQL()
    .INSERT_INTO("PERSON")
    .INTO_COLUMNS("ID", "FULL_NAME")
    .INTO_VALUES("#{id}", "#{fullName}")
    .toString();
}

public String updatePersonSql() {
  return new SQL()
    .UPDATE("PERSON")
    .SET("FULL_NAME = #{fullName}", "DATE_OF_BIRTH = #{dateOfBirth}")
    .WHERE("ID = #{id}")
    .toString();
}

4 SqlBuilder 和 SelectBuilder(已废弃)

Before version 3.2 we took a bit of a different approach, by utilizing a ThreadLocal variable to mask some of the language limitations that make Java DSLs a bit cumbersome. However, this approach is now deprecated, as modern frameworks have warmed people to the idea of using builder-type patterns and anonymous inner classes for such things. Therefore the SelectBuilder and SqlBuilder classes have been deprecated.
在 3.2 版本之前,我们使用了一点不同的方法,通过使用一个 ThreadLocal 参数来掩饰一些使 Java DSL 变的笨重的语言限制。然而,这个方法现在已经废弃了,现在的框架都欢迎人们使用 builder-type 模式和匿名内部类的方式。因此,SelectBuilder 和 SqlBuilder 类被废弃了。

The following methods apply to only the deprecated SqlBuilder and SelectBuilder classes.
下面的方法仅适用于已经废弃的 SelectBuilder 和 SqlBuilder 类。

  • BEGIN() /RESET()
    These methods clear the ThreadLocal state of the SelectBuilder class, and prepare it for a new statement to be built. BEGIN() reads best when starting a new statement. RESET() reads best when clearing a statement in the middle of execution for some reason (perhaps if the logic demands a completely different statement under some conditions).
    这些方法用来清空 SelectBuilder 类的 ThreadLocal 状态,并且为一个新的语句构建准备它。在开始一个新的语句时 BEGIN() 读取效果最好。 在执行期间因为一些原因(在某些条件下可能是逻辑上需要一个完全不同的语句)来清空一条语句时,RESET() 读取效果最好。

  • SQL()
    This returns the generated SQL() and resets the SelectBuilder state (as if BEGIN() or RESET() were called). Thus, this method can only be called ONCE!
    返回生成的 SQL() 并重置 SelectBuilder 的状态(就像 BEGIN() 或 RESET())。因此,这个方法只能被调用一次。

The SelectBuilder and SqlBuilder classes are not magical, but it's important to know how they work. SelectBuilder and SqlBuilder use a combination of Static Imports and a ThreadLocal variable to enable a clean syntax that can be easily interlaced with conditionals. To use them, you statically import the methods from the classes like this (one or the other, not both):
SelectBuilder 和 SqlBuilder 类并不神奇,但是知道他们是如何工作是很重要的。SelectBuilder 和 SqlBuilder 类使用静态导入和一个 ThreadLocal 参数的组合来开启可以很容易地同条件句交织的整洁语法。使用它们,你可以像下面这样静态导入类(两者取其一):

import static org.apache.ibatis.jdbc.SelectBuilder.*;
import static org.apache.ibatis.jdbc.SqlBuilder.*;

这允许我们像这样来创建方法:

/* DEPRECATED */
public String selectBlogsSql() {
  BEGIN(); // 清空 ThreadLocal 变量
  SELECT("*");
  FROM("BLOG");
  return SQL();
}
/* DEPRECATED */
private String selectPersonSql() {
  BEGIN(); // 清空 ThreadLocal 变量
  SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
  SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
  FROM("PERSON P");
  FROM("ACCOUNT A");
  INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID");
  INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID");
  WHERE("P.ID = A.ID");
  WHERE("P.FIRST_NAME like ?");
  OR();
  WHERE("P.LAST_NAME like ?");
  GROUP_BY("P.ID");
  HAVING("P.LAST_NAME like ?");
  OR();
  HAVING("P.FIRST_NAME like ?");
  ORDER_BY("P.ID");
  ORDER_BY("P.FULL_NAME");
  return SQL();
}

最后

说明:MyBatis 官网提供了简体中文的翻译,但个人觉得较为生硬,甚至有些地方逻辑不通,于是自己一个个重新敲着翻译的(都不知道哪里来的自信...),有些地方同官网翻译有出入,有些倔强地保留了自己的,有的实在别扭则保留了官网的,这些都会在实践中一一更正。鉴于个人英文能力有限,文章中保留了官方文档原英文介绍(个别地方加以调整修剪),希望有缘看到这里的朋友们能够有自己的理解,不会被我可能错误或不合理的翻译带跑偏(〃'▽'〃),欢迎指正!

当前版本:mybatis-3.5.0
官网文档:MyBatis
官网翻译:MyBatis 简体中文
项目实践:MyBatis Learn

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,406评论 5 475
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,976评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,302评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,366评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,372评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,457评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,872评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,521评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,717评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,523评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,590评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,299评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,859评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,883评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,127评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,760评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,290评论 2 342

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,279评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,331评论 0 23
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,440评论 0 13
  • 201年2月16日 昨天的计划全部给泡汤了,昨天晚上儿子开始发烧,忙的我一晚上都没有睡好,早上7点半也不想...
    杜书晓阅读 73评论 2 1
  • 苏子瞻谪居黄州五个年头,赤壁是他最喜欢去的地方之一,仅有文字记载就有十几次,其中元丰五年(1082)的三次...
    见长空万里阅读 484评论 0 2