java – ORMLite中有多个组合OR条件
|
我喜欢这样的查询: select data from table
where (x > 1 and x < 100)
or (x > 250 and x < 300)
在ORMlite中,可以使用以下代码: 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)
)
虽然如果事先知道条件,在编码的时候,我需要动态添加条件. 基本上该方法public com.j256.ormlite.stmt.Where< T,ID>或者(com.j256.ormlite.stmt.Where< T,ID> left,com.j256.ormlite.stmt.Where< T,ID> right,ID>其他)还不够. 感谢任何建议. 解决方法在 ORMLite Where.or(其中< T,Where< T,ID> …其他)是语法黑客的一点.你打电话时:w.or(
w.gt("x",300)
);
or()方法得到的是: w.or(w,w); 你真的可以将其重写为: w.gt("x",100);
w.gt("x",300);
w.or(w,w);
该方法只使用参数来计算需要从堆栈中弹出多少个子句.当您调用gt和lt和其他人时,它会推送子句堆栈上的项目. and()方法将1个项目从堆栈中抽出,然后在以后再获取另一个项目.我们做这些语法黑客,因为我们要支持线性,链接和基于参数的查询: w.gt("x",1);
w.and();
w.lt("x",100);
与: w.gt("x",100);
与: w.and(w.gt("x",1),w.lt("x",100));
但这意味着您有权力通过使用Where.or(int many)方法来极大地简化您的代码.所以在上面的例子中也可以是: w.gt("x",300);
// create an OR statement from the last 2 clauses on the stack
w.or(2);
所以你根本不需要条件列表.所有你需要的是一个柜台.所以你可以做一些事情: 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);
}
如果我只能是1到5,那么你可以使用values.size()并跳过clauseC.请注意,如果我们只添加一个子句,那么我们可以完全跳过OR方法调用. 呵呵,以下声明不行: target.or().raw(first.getStatement()); 因为目标和第一个是相同的对象. first.getStatement()转储整个SQL WHERE子句,我不认为是你想要的. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
