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

标签 android sql hibernate orm ormlite

首先请看下面的代码。我以前使用过各种 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();

最佳答案

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

关于Android Ormlite - 使用条件 where 子句构建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25474777/

相关文章:

Android XML 百分比符号

sql - Oracle 如何将生成的列添加到选择 *

php - MySQL 将多行查询连接到一列中

java - 如何将 Wordnet 同义词与 Hibernate 搜索结合使用?

Android 2.3.4 电话管理器

java - Android 将值传递给另一个 Activity

android - 有没有人有Delphi的Android访问USB类的例子?

sql - 如何使用最后插入的 ID 将行插入到另一个表中?

java - hibernate 条件中的表达式

java - hibernate 程序不终止