通过Morphia使用$ in运算符-做错了吗? [英] Using the $in operator through Morphia - doing it wrong?

查看:59
本文介绍了通过Morphia使用$ in运算符-做错了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为通用博客应用程序的一部分,我具有以下Play Framework实体(使用Morphia进行持久化):

I have the following Play Framework entity (using Morphia for persistence) as part of a generic blogging app:

@Entity
public class Comment extends Model {

    ...

    @Reference
    @Indexed
    public SiteUser commenter;

    public static List<Comment> getLastCommentsByUsers(final List<SiteUser> users) {
        final Query<Comment> query ds().createQuery(Comment.class);
        query.field(commenter).hasAnyOf(users);
        return query.asList();
    }

}

SiteUser:

@Entity(noClassnameStored=true)
public class SiteUser extends AbstractUser {

    public String realName;

}

AbstractUser:

AbstractUser:

public class AbstractUser extends Model {

    @Indexed(value= IndexDirection.DESC, unique = true)
    public String emailAddress;

    @Required
    public String password;
}

方法getLastCommentsByUsers()应该由用户在users参数中返回所有注释,但是我总是得到空的List. Commment是一个单独的集合的原因是为了能够使某些用户跨关联的Post检索最后X个Comment,如果Comment嵌入在Post中则不可能集合.

The method getLastCommentsByUsers() is supposed to return all comments by the users in the users parameter, but I always get an empty List back. The reason that Commment is a separate collection is to be able to retrieve last X Comments by certain users across their associated Posts, which isn't possible if the Comment is embedded in the Post collection.

查询是否有问题(我应该使用hasAnyOf以外的其他内容),还是关系映射存在问题-我应该使用ObjectId吗?

Is there something wrong with my query (should I be using something other than hasAnyOf), or is it a problem with the relationship mapping - should I be using ObjectId instead?

推荐答案

您应使用List<Key<SiteUser>>进行查询:

public static List<Comment> getLastCommentsByUsers(final List<SiteUser> users) {
    final Query<Comment> query ds().createQuery(Comment.class);
    query.field(commenter).hasAnyOf(toKeys(users)); // convert to keys
    return query.asList();
}

public static List<Key<SiteUser>> toKeys(List<SiteUser> users) {
    List<Key<SiteUser>> keys = new ArrayList<Key<SiteUser>>();
    for(SiteUser user: users) {
        keys.add(ds().getMapper().getKey(user));
    }
    return keys;
}

或者您也可以通过以下方式获取密钥:

Or you can just get the keys by:

List<Key<SiteUser>> keys = ds().createQuery(SiteUser.class).query().filter(...).asKeyList();

这篇关于通过Morphia使用$ in运算符-做错了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆