The SQL Builder Class

The Problem

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:

  1. String sql = "SELECT P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME, "
  2. "P.LAST_NAME,P.CREATED_ON, P.UPDATED_ON " +
  3. "FROM PERSON P, ACCOUNT A " +
  4. "INNER JOIN DEPARTMENT D on D.ID = P.DEPARTMENT_ID " +
  5. "INNER JOIN COMPANY C on D.COMPANY_ID = C.ID " +
  6. "WHERE (P.ID = A.ID AND P.FIRST_NAME like ?) " +
  7. "OR (P.LAST_NAME like ?) " +
  8. "GROUP BY P.ID " +
  9. "HAVING (P.LAST_NAME like ?) " +
  10. "OR (P.FIRST_NAME like ?) " +
  11. "ORDER BY P.ID, P.FULL_NAME";

The Solution

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:

  1. private String selectPersonSql() {
  2. return new SQL() {{
  3. SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
  4. SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
  5. FROM("PERSON P");
  6. FROM("ACCOUNT A");
  7. INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID");
  8. INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID");
  9. WHERE("P.ID = A.ID");
  10. WHERE("P.FIRST_NAME like ?");
  11. OR();
  12. WHERE("P.LAST_NAME like ?");
  13. GROUP_BY("P.ID");
  14. HAVING("P.LAST_NAME like ?");
  15. OR();
  16. HAVING("P.FIRST_NAME like ?");
  17. ORDER_BY("P.ID");
  18. ORDER_BY("P.FULL_NAME");
  19. }}.toString();
  20. }

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.

The SQL Class

Here are some examples:

  1. // Anonymous inner class
  2. public String deletePersonSql() {
  3. return new SQL() {{
  4. DELETE_FROM("PERSON");
  5. WHERE("ID = #{id}");
  6. }}.toString();
  7. }
  8. // Builder / Fluent style
  9. public String insertPersonSql() {
  10. String sql = new SQL()
  11. .INSERT_INTO("PERSON")
  12. .VALUES("ID, FIRST_NAME", "#{id}, #{firstName}")
  13. .VALUES("LAST_NAME", "#{lastName}")
  14. .toString();
  15. return sql;
  16. }
  17. // With conditionals (note the final parameters, required for the anonymous inner class to access them)
  18. public String selectPersonLike(final String id, final String firstName, final String lastName) {
  19. return new SQL() {{
  20. SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME");
  21. FROM("PERSON P");
  22. if (id != null) {
  23. WHERE("P.ID like #{id}");
  24. }
  25. if (firstName != null) {
  26. WHERE("P.FIRST_NAME like #{firstName}");
  27. }
  28. if (lastName != null) {
  29. WHERE("P.LAST_NAME like #{lastName}");
  30. }
  31. ORDER_BY("P.LAST_NAME");
  32. }}.toString();
  33. }
  34. public String deletePersonSql() {
  35. return new SQL() {{
  36. DELETE_FROM("PERSON");
  37. WHERE("ID = #{id}");
  38. }}.toString();
  39. }
  40. public String insertPersonSql() {
  41. return new SQL() {{
  42. INSERT_INTO("PERSON");
  43. VALUES("ID, FIRST_NAME", "#{id}, #{firstName}");
  44. VALUES("LAST_NAME", "#{lastName}");
  45. }}.toString();
  46. }
  47. public String updatePersonSql() {
  48. return new SQL() {{
  49. UPDATE("PERSON");
  50. SET("FIRST_NAME = #{firstName}");
  51. WHERE("ID = #{id}");
  52. }}.toString();
  53. }
MethodDescription
  • 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_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.
  • 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.
  • 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.
  • 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.
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.
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.
  • 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.
  • 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.
  • 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.
  • LIMIT(String)
  • LIMIT(int)
Appends a LIMIT clause. This method valid when use together with SELECT(), UPDATE() and DELETE(). And this method is designed to use together with OFFSET() when use SELECT(). (Available since 3.5.2)
  • OFFSET(String)
  • OFFSET(long)
Appends a OFFSET clause. This method valid when use together with SELECT(). And this method is designed to use together with LIMIT(). (Available since 3.5.2)
  • OFFSET_ROWS(String)
  • OFFSET_ROWS(long)
Appends a OFFSET n ROWS clause. This method valid when use together with SELECT(). And this method is designed to use together with FETCH_FIRST_ROWS_ONLY(). (Available since 3.5.2)
  • FETCH_FIRST_ROWS_ONLY(String)
  • FETCH_FIRST_ROWS_ONLY(int)
Appends a FETCH FIRST n ROWS ONLY clause. This method valid when use together with SELECT(). And this method is designed to use together with OFFSET_ROWS(). (Available since 3.5.2)
DELETE_FROM(String)Starts a delete statement and specifies the table to delete from. Generally this should be followed by a WHERE statement!
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.
  • SET(String)
  • SET(String…)
Appends to the “set” list for an update statement.
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.
VALUES(String, String)Appends to an insert statement. The first parameter is the column(s) to insert, the second parameter is the value(s).
INTO_COLUMNS(String…)Appends columns phrase to an insert statement. This should be call INTO_VALUES() with together.
INTO_VALUES(String…)Appends values phrase to an insert statement. This should be call INTO_COLUMNS() with together.
ADD_ROW()Add new row for bulk insert. (Available since 3.5.2)

NOTE It is important to note that SQL class writes LIMIT, OFFSET, OFFSET n ROWS and FETCH FIRST n ROWS ONLY clauses into the generated statement as is. In other words, the library does not attempt to normalize those values for databases that don’t support these clauses directly. Therefore, it is very important for users to understand whether or not the target database supports these clauses. If the target database does not support these clauses, then it is likely that using this support will create SQL that has runtime errors.

Since version 3.4.2, you can use variable-length arguments as follows:

  1. public String selectPersonSql() {
  2. return new SQL()
  3. .SELECT("P.ID", "A.USERNAME", "A.PASSWORD", "P.FULL_NAME", "D.DEPARTMENT_NAME", "C.COMPANY_NAME")
  4. .FROM("PERSON P", "ACCOUNT A")
  5. .INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID", "COMPANY C on D.COMPANY_ID = C.ID")
  6. .WHERE("P.ID = A.ID", "P.FULL_NAME like #{name}")
  7. .ORDER_BY("P.ID", "P.FULL_NAME")
  8. .toString();
  9. }
  10. public String insertPersonSql() {
  11. return new SQL()
  12. .INSERT_INTO("PERSON")
  13. .INTO_COLUMNS("ID", "FULL_NAME")
  14. .INTO_VALUES("#{id}", "#{fullName}")
  15. .toString();
  16. }
  17. public String updatePersonSql() {
  18. return new SQL()
  19. .UPDATE("PERSON")
  20. .SET("FULL_NAME = #{fullName}", "DATE_OF_BIRTH = #{dateOfBirth}")
  21. .WHERE("ID = #{id}")
  22. .toString();
  23. }

Since version 3.5.2, you can create insert statement for bulk insert as follow:

  1. public String insertPersonsSql() {
  2. // INSERT INTO PERSON (ID, FULL_NAME)
  3. // VALUES (#{mainPerson.id}, #{mainPerson.fullName}) , (#{subPerson.id}, #{subPerson.fullName})
  4. return new SQL()
  5. .INSERT_INTO("PERSON")
  6. .INTO_COLUMNS("ID", "FULL_NAME")
  7. .INTO_VALUES("#{mainPerson.id}", "#{mainPerson.fullName}")
  8. .ADD_ROW()
  9. .INTO_VALUES("#{subPerson.id}", "#{subPerson.fullName}")
  10. .toString();
  11. }

Since version 3.5.2, you can create select statement for limiting search result rows clause as follow:

  1. public String selectPersonsWithOffsetLimitSql() {
  2. // SELECT id, name FROM PERSON
  3. // LIMIT #{limit} OFFSET #{offset}
  4. return new SQL()
  5. .SELECT("id", "name")
  6. .FROM("PERSON")
  7. .LIMIT("#{limit}")
  8. .OFFSET("#{offset}")
  9. .toString();
  10. }
  11. public String selectPersonsWithFetchFirstSql() {
  12. // SELECT id, name FROM PERSON
  13. // OFFSET #{offset} ROWS FETCH FIRST #{limit} ROWS ONLY
  14. return new SQL()
  15. .SELECT("id", "name")
  16. .FROM("PERSON")
  17. .OFFSET_ROWS("#{offset}")
  18. .FETCH_FIRST_ROWS_ONLY("#{limit}")
  19. .toString();
  20. }

SqlBuilder and SelectBuilder (DEPRECATED)

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.

The following methods apply to only the deprecated SqlBuilder and SelectBuilder classes.

MethodDescription
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).
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!

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

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

This allows us to create methods like these:

  1. /* DEPRECATED */
  2. public String selectBlogsSql() {
  3. BEGIN(); // Clears ThreadLocal variable
  4. SELECT("*");
  5. FROM("BLOG");
  6. return SQL();
  7. }
  1. /* DEPRECATED */
  2. private String selectPersonSql() {
  3. BEGIN(); // Clears ThreadLocal variable
  4. SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME");
  5. SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON");
  6. FROM("PERSON P");
  7. FROM("ACCOUNT A");
  8. INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID");
  9. INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID");
  10. WHERE("P.ID = A.ID");
  11. WHERE("P.FIRST_NAME like ?");
  12. OR();
  13. WHERE("P.LAST_NAME like ?");
  14. GROUP_BY("P.ID");
  15. HAVING("P.LAST_NAME like ?");
  16. OR();
  17. HAVING("P.FIRST_NAME like ?");
  18. ORDER_BY("P.ID");
  19. ORDER_BY("P.FULL_NAME");
  20. return SQL();
  21. }