18
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

動的クエリーの文字列構築を後置ifで見やすくする

Posted at

動的にクエリー文字列を構築する場合、通常はif文で文字列の追加を制御するが、if文だらけになるとどうしてもクエリー部分の可読性が低くなってしまう。
これを後置ifを使って書くと、ほんの少しだけ見やすいコードになる。

後置ifとはperl等で使える構文で、実行文の後ろに条件を書く構文の事。
書き方が違うだけで内容は全く同じ。

一般的なif文
if 条件 then 実行文;
後置if
実行文 if 条件;

後置ifが使える言語は少ないが、後置if風に書くためのビルダーを作成することで対応できる。

以下、JavaでJPQLの構築例。

Before

通常のif文で動的クエリーを組み立てる
StrinbBuilder sb = new StringBuilder();
sb.append("select u");
sb.append(" from User u");
if (followTagName != null) sb.append(" join u.followTags ft");
sb.append(" where true");
if (name != null)          sb.append(" and u.name like :name");
if (email != null)         sb.append(" and u.email like :email");
if (followTagName != null) sb.append(" and ft.name = :followTagName");

After

後置if風に書くためのビルダーで組み立てる
new QueryBuilder()
    .append("select u")
    .append(" from User u")
    .append(" join u.followTags ft",         followTagName != null)
    .append(" where true")
    .append(" and u.name like :name",        name != null)
    .append(" and u.email like :email",      email != null)
    .append(" and ft.name = :followTagName", followTagName != null);
QueryBuilder.java
public class QueryBuilder {
    StringBuilder sb = new StringBuilder();
    public QueryBuilder append(String str) {
        sb.append(str);
        return this;
    }
    /**
     * conditionが真のときだけstrを追加する。
     */
    public QueryBuilder append(String str, boolean condition) {
        if (condition) append(str);
        return this;
    }
    public String toString() {
        return sb.toString();
    }
}
18
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?