Jonathan S. Fisher
Jonathan S. Fisher

Reputation: 8827

Mybatis, Enclosed OR with SQL builder

I cannot figure out how to get MyBatis to generate an enclosed or statement:

WHERE x.token = ? AND (
  (x.scene = 'A' OR x.scene = 'B'))

This is a surprisingly simple operation they've made very difficult. I can't find it in the JavaDoc: http://static.javadoc.io/org.mybatis/mybatis/3.4.5/org/apache/ibatis/jdbc/SQL.html

Upvotes: 0

Views: 247

Answers (1)

It can't be done in the current version of mybatis (3.4.6).

You can either use the whole subexpression like this:

WHERE("x.token = ?");
WHERE("(x.scene = 'A' OR x.scene = 'B')");

or create you own function if you have many/variable number of operands to OR:

WHERE("x.token = ?");
WHERE(OR("x.scene = 'A'", "x.scene = 'B'"));

Where OR is defined (using guava Joiner) as:

Joiner OR_JOINER = Joiner.on(" OR ");

private String OR(String ... operands) {
    return String.format("(%s)", OR_JOINER.join(operands));
}

Upvotes: 2

Related Questions