Using the $in operator through Morphia - doing it wrong?
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:
public class AbstractUser extends Model {
@Indexed(value= IndexDirection.DESC, unique = true)
public String emailAddress;
@Required
public String password;
}开发者_Go百科
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.
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?
I use the in() method with a list or set and its working perfectly. Here's a snippet:
List<String> keywordList;
List<Product> products = Product.find().field("keywords").in(keywordList).asList();
This should work for collection of embedded or references too.
You should use List<Key<SiteUser>>
to query:
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();
精彩评论