Quantcast
Channel: sql – Java, SQL and jOOQ.
Viewing all articles
Browse latest Browse all 426

MyBatis’ Wicked Statement Builders

$
0
0

Now here’s one of the most wicked API’s I’ve seen in a while!

MyBatis is well-known as a database abstraction framework on top of JDBC, allowing for externalising SQL into files, loading them at appropriate places in your Java code. For those of you who like this approach, you may be used to statements similar to this one here, taken from the MyBatis documentation:

<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>

This is MyBatis alright, you think? You haven’t seen everything. MyBatis also has statement builders. Not just any type of statement builders. They make your Java code look like SQL. Check this out:

private String selectPersonSql() {
  BEGIN(); // Clears ThreadLocal variable
  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();
}

… jeez, that is one of the funniest ideas I’ve ever seen. A ThreadLocal to keep the SQL statement currently being rendered!! And an API just … err … adding Strings to an internal StringBuilder? Wow.

You can decide for yourself whether you like this or not. But you can’t say these guys aren’t creative ;-) Be sure to read the full docs to learn also about how to write INSERT, UPDATE and DELETE:

http://www.mybatis.org/core/statement-builders.html


Filed under: java, sql Tagged: April Fool's, database abstraction, funny API, mybatis, sql, statement builder, what the heck

Viewing all articles
Browse latest Browse all 426

Trending Articles