通过比较字段进行morphia查询

时间:2016-03-07 08:34:08

标签: java mongodb morphia

public class MyObject{
    private String string1;
    private Long long1;
    private String string2;
    .......//other states
}

我正在尝试做的事情就像是

public List find(MyObject o){
    return morphiaDatastore.find(o);
}

我期待所有其字符串1为“someValue”且string3为“otherValue”的MyObject。我如何使用吗啡呢?我知道我们可以使用标准查询,但是用户可以选择任何现有字段作为标准,标准查询方法也不能很好地处理对象结构重构。

1 个答案:

答案 0 :(得分:0)

您可以通过创建 Query 对象并指定 filter 来获得所需的结果来实现此目的:

Query query = datastore.createQuery(MyObject.class)
                       .filter("string1 = ", "someValue")
                       .filter("string3 = ", "otherValue");

在上文中,指定要查询的类MyObject,并过滤到 createQuery() 方法。定义查询后,使用asList()方法访问结果:

List<MyObject> objects = query.asList();

Morphia的过滤器运算符紧密映射到MongoDB查询中使用的查询运算符。上述查询中的=运算符类似于MongoDB中的 $eq 运算符。

作为过滤查询的替代方案,Morphia提供了用于构建查询的 fluent 界面。例如,以下fluent-interface查询与前面的过滤器查询相同:

Query query = datastore.createQuery(MyObject.class)
                       .field("string1").equal("someValue")
                       .field("string3").equal("otherValue");