【问题标题】:Android Ormlite - Building queries with conditional where clauseAndroid Ormlite - 使用条件 where 子句构建查询
【发布时间】:2014-08-24 18:13:00
【问题描述】:

首先请看下面的代码。我以前使用过各种 ORM(Hibernate、DataMapper),但在 ORMLite 中我面临一个非常棘手的问题。查看我的代码,我将设置 where 条件子句。根据 ormlite api and() 方法应该放在两个 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();

【问题讨论】:

    标签: android sql hibernate orm ormlite


    【解决方案1】:

    我自己没有使用过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

    【讨论】:

    • 如果第一个 IF 语句没有执行怎么办?然后 where 子句首先得到一个 and() 。你明白吗?
    • @mahbub.kuet,错过了那部分。修改了代码,但是会有一个比我发布的更优雅的解决方案。如果我有更好的主意,我会编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2013-10-11
    • 2012-04-20
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 2014-08-24
    相关资源
    最近更新 更多