Using the $in operator through Morphia - doing it wrong?

怎甘沉沦 提交于 2019-12-07 06:36:43

问题


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;
}

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.

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?


回答1:


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();



回答2:


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.



来源:https://stackoverflow.com/questions/6124236/using-the-in-operator-through-morphia-doing-it-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!