通过Morphia使用$ in运算符-做错了吗? [英] Using the $in operator through Morphia - doing it wrong?
问题描述
作为通用博客应用程序的一部分,我具有以下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 Comment
s by certain users across their associated Post
s, 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屋!