Android Ormlite - 使用条件where子句构建查询

时间:2014-08-24 18:13:00

标签: android sql hibernate orm ormlite

首先请查看下面的代码。我之前使用过各种ORM(Hibernate,DataMapper),但在ORMLite中我遇到了一个非常戏弄的问题。看看我的代码,我将设置where条款的条款。根据ormlite api和()方法应该放在两个where子句的中间。在我的情况下,仍有一个额外的and()方法,在ORMLite中是不允许的。

那么这种情况下最好的解决方案是什么?

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();

1 个答案:

答案 0 :(得分:3)

Haven并没有自己使用ORMLite,但我认为你可以这样做

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;
}

您可以找到更多in docs