虽然如果事先知道条件并且在编码时很好,但我需要动态添加条件。
在ORMLite Where.or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) 中有点语法技巧。当你打电话时:
w.or(
w.gt("x", 1).and().lt("x", 100),
w.gt("x", 250).and().lt("x", 300)
);
or() 方法得到的是:
w.or(w, w);
你真的可以把它改写成:
w.gt("x", 1).and().lt("x", 100);
w.gt("x", 250).and().lt("x", 300);
w.or(w, w);
or 方法只使用参数来计算它需要从堆栈中弹出多少子句。当您调用 gt 和 lt 等时,它会将项目推送到子句堆栈中。 and() 方法从堆栈中拉出 1 个项目,然后在将来获取另一个项目。我们进行这些语法修改是因为我们希望支持线性、链式和基于参数的查询:
w.gt("x", 1);
w.and();
w.lt("x", 100);
对比:
w.gt("x", 1).and().lt("x", 100);
对比:
w.and(w.gt("x", 1), w.lt("x", 100));
但这意味着您可以通过使用Where.or(int many) 方法极大地简化您的代码。所以在上面or的例子中也可以是:
w.gt("x", 1).and().lt("x", 100);
w.gt("x", 250).and().lt("x", 300);
// create an OR statement from the last 2 clauses on the stack
w.or(2);
所以你根本不需要conditions 列表。您只需要一个计数器。所以你可以这样做:
int clauseC = 0;
for (int i : values) {
if (i == 1) {
w.le(C_PREIS, 1000);
clauseC++;
} else if (i == 2) {
w.gt(C_PREIS, 1000).and().le(C_PREIS, 2500);
clauseC++;
} else if (i == 3) {
w.gt(C_PREIS, 2500).and().le(C_PREIS, 5000);
clauseC++;
} else if (i == 4) {
w.gt(C_PREIS, 5000).and().le(C_PREIS, 10000);
clauseC++;
} else if (i == 5) {
w.gt(C_PREIS, 10000);
clauseC++;
}
}
// create one big OR(...) statement with all of the clauses pushed above
if (clauseC > 1) {
w.or(clauseC);
}
如果i 只能是 1 到 5,那么您可以直接使用 values.size() 并跳过 clauseC。请注意,如果我们只添加一个子句,那么我们可以完全跳过 OR 方法调用。
哦,下面的语句不会起作用:
target.or().raw(first.getStatement());
因为target 和first 是同一个对象。 first.getStatement() 转储整个 SQL WHERE 子句,我认为这不是你想要的。