Android Ormlite-使用条件where子句构建查询
首先请看下面的代码。我以前使用过各种ORM(Hibernate、DataMapper),但在ORMLite中,我面临着一个非常棘手的问题。在我的代码中,我要设置where子句,它是有条件的。根据OrMLITE API和()方法应该放置在两个WHERE子句的中间。在我的例子中,还有一个额外的and()方法,这在ORMLite中是不允许的 那么,在这种情况下,最好的解决方案是什么Android Ormlite-使用条件where子句构建查询,android,sql,hibernate,orm,ormlite,Android,Sql,Hibernate,Orm,Ormlite,首先请看下面的代码。我以前使用过各种ORM(Hibernate、DataMapper),但在ORMLite中,我面临着一个非常棘手的问题。在我的代码中,我要设置where子句,它是有条件的。根据OrMLITE API和()方法应该放置在两个WHERE子句的中间。在我的例子中,还有一个额外的and()方法,这在ORMLite中是不允许的 那么,在这种情况下,最好的解决方案是什么 if(filter.getInstituionId() != null) builder.where().eq(
if(filter.getInstituionId() != null)
builder.where().eq(BuyPostItem.FIELD_INSTITUTION_ID, filter.getInstituionId()).and();
if(filter.getBookCategoryId() != null)
builder.where().eq(BuyPostItem.FIELD_CATEGORY_ID, filter.getBookCategoryId()).and();
if(filter.getMinPrice() != null)
builder.where().ge(BuyPostItem.FIELD_EXPECTED_PRICE, filter.getMinPrice()).and();
if(filter.getMaxPrice() != null)
builder.where().le(BuyPostItem.FIELD_EXPECTED_PRICE, filter.getMaxPrice()).and();
我自己没有使用过
或mlite
,但我认为你可以这样做
Where where = builder.where();
// dirty hack
boolean hasAnythingBeforeThis = false;
if(filter.getInstituionId() != null) {
where.eq(BuyPostItem.FIELD_INSTITUTION_ID, filter.getInstituionId());
hasAnythingBeforeThis = true;
}
if(filter.getBookCategoryId() != null) {
if(hasAnythingBeforeThis){
where.and();
}
where.eq(BuyPostItem.FIELD_CATEGORY_ID, filter.getBookCategoryId());
hasAnythingBeforeThis = true;
}
if(filter.getMinPrice() != null) {
if(hasAnythingBeforeThis){
where.and();
}
where.ge(BuyPostItem.FIELD_EXPECTED_PRICE, filter.getMinPrice());
hasAnythingBeforeThis = true;
}
if(filter.getMaxPrice() != null) {
if(hasAnythingBeforeThis){
where.and();
}
where.le(BuyPostItem.FIELD_EXPECTED_PRICE, filter.getMaxPrice());
hasAnythingBeforeThis = true;
}
您可以了解更多信息如果未执行first if语句怎么办?然后where子句首先得到and()。你明白吗?@mahbub.kuet,错过了那部分。修改了代码,但会有一个更优雅的解决方案,我所发布的。如果我有更好的想法,我会编辑。