MyBatis "or" criteria

Fergus MacDubh picture Fergus MacDubh · Oct 22, 2014 · Viewed 13.3k times · Source

I want to create a query with MyBatis, which will produce something like:

SELECT first_field, second_filed, third_field
WHERE first_field > 1 AND (second_field > 0 OR third_field < 0)

How could I construct that with Criteria objects?

Answer

Mike picture Mike · Nov 6, 2015

Since a AND (b OR c) is the same as (a AND b) or (a AND c)

TestTableExample example = new TestTableExample();
example.createCriteria()
  .andField1GreaterThan(1)
  .andField2GreaterThan(0);
example.or(example.createCriteria()
  .andField1GreaterThan(1)
  .andField3LessThan(0));

then sit back and let the SQL optimizer figure it out.