Objectify - 如果不为null则设置过滤器

时间:2017-02-13 12:23:53

标签: google-app-engine objectify

我有一个带有一些可空查询参数的资源。 我想从DB(GAE DataStore)返回相关实体 我是否有更短或更漂亮的方法(我正在寻找类似'set if not null'的方法)?

这是我的代码:

var query: Query<Kind> = ObjectifyService.ofy().load().type(Kind::class.java)

if (name != null) {
query = query.filter("name ==", name)
} else if (gender != null) {
query = query.filter("gender ==", gender)
} else if (address != null) {
query = query.filter("timing ==", address)
}

return query....
}

1 个答案:

答案 0 :(得分:1)

不幸的是,Objectify中没有这样的东西。

如果您在过滤器中使用了很多参数,则一种流行的方法是builder模式:

public class MyFileProvider extends FileProvider {
    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
        //doesn't print anything
        Log.d(MyFileProvider.class.getSimpleName(), uri.toString()); 
        return super.openFile(uri, mode);
    }
}

然后:

public class QueryBuilder {
    public static final Class<Kind> TYPE = Kind.class;
    private Query<Kind> query;

    public QueryBuilder() {
        query = ofy().load().type(TYPE);
    }

    public QueryBuilder name(String name) {
        return setIfNotNull("name", name);
    }

    public QueryBuilder gender(String gender) {
        return setIfNotNull("gender", gender);
    }

    public QueryBuilder address(String address) {
        return setIfNotNull("address", address);
    }

    public Query<Kind> build() {
        return query;
    }

    private QueryBuilder setIfNotNull(String name, Object value) {
        if (value != null) {
            query = query.filter(name, value);
        }
        return this;
    }

}