I like to have a query like this:
select data from table
where (x > 1 and x < 100)
or (x > 250 and x < 300)
In ORMlite, that’s possible using this code:
final QueryBuilder<Data,Integer> qb = queryBuilder();
final Where<Data, Integer> w = qb.where();
w.or(
w.gt("x", 1).and().lt("x", 100),
w.gt("x", 250).and().lt("x", 300)
)
While thats great if one knows the conditions beforehand & at the time of coding, I need the conditions to be dynamically added.
Basically that method public com.j256.ormlite.stmt.Where<T,ID> or(com.j256.ormlite.stmt.Where<T,ID> left, com.j256.ormlite.stmt.Where<T,ID> right, com.j256.ormlite.stmt.Where<T,ID>... others) is not enough.
It needs another or method that supports a ArrayList of Where conditions.
Thanks for any suggestions.
In ORMLite
Where.or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others)is a bit of a syntax hack. When you call:What the
or()method gets is:You really could rewrite it as:
The
ormethod there is only using the arguments to count how many clauses it needs to pop off of the stack. When you callgtandltand others, it pushes items on a clause stack. Theand()method pulls 1 item off the stack and then takes another item in the future. We do these syntax hacks because we want to support linear, chained, and argument based queries:versus:
versus:
But this means that you have the power to simplify your code immensely by using the Where.or(int many) method. So in the
orexample above can also be:So you don’t need the
conditionslist at all. All you need is a counter. So you could do something like:If
ican only be 1 to 5 then you can just usevalues.size()and skip theclauseC. Notice that if we are only adding one clause then we can skip theORmethod call entirely.Oh, and the following statement will not work:
because
targetandfirstare the same object.first.getStatement()dumps the entire SQLWHEREclause which I don’t think is what you want.