Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Morphia Query by Reference ObjectID

Here's my entity's definition:

@Entity("Comment")
public class Comment extends BaseEntity {

    @Reference
    private Merchant merchant;

    ...
}

@Entity("Merchant")
class Merchant extends BaseEntity{
    @Id
    @Property("id")
    protected ObjectId id;

    ...
}

And here's my data:

comment:{
"_id": ObjectId("546c1ac64652e5180dc21577"),
"merchant" : DBRef("Merchant", ObjectId("546c1ac64652e5180dc21576")),

...
}

When I create a Query like:

Query<Comment> query = ds.createQuery(Comment.class);
query.field("merchant").equal(new ObjectId("546c1ac64652e5180dc21576"));

commentDao.findOne(query);

There's no result returned, I'd like to ask which is the right way to query a comment data with merchant's ObjectId?

Thanks for your help.

like image 214
Zachary Tang Avatar asked Jun 20 '26 06:06

Zachary Tang


1 Answers

Query<Comment> query = ds.find(Comment.class).disableValidation()
    .field("Merchant").equal(new Key<>(Merchant.class, merchantId);

I think you need to disable validation, otherwise you'll see some rather unnecessary warning.

You can query the DBRef ID directly, but since DBRef itself is typed, I'd not circumvent it unless you have some valid reason.

like image 138
xeraa Avatar answered Jun 21 '26 23:06

xeraa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!