MongoDB DBRef handling inside GWT's RequestFactory function call

153 Views Asked by At

I have question related to DBRef of MongoDB. Imagine this scenario:

Group{
...
 "members" : [
            {
                    "$ref" : "User",
                    "$id" : ObjectId("505857a4e4b5541060863061")
            },
            {
                    "$ref" : "User",
                    "$id" : ObjectId("50586411e4b0b31012363208")
            },
            {
                    "$ref" : "User",
                    "$id" : ObjectId("50574b9ce4b0b3106023305c")
            },
]
...
}

So given group document has 3 user DBRef. Where in java class of Group, members is tagged with morphia as @Reference:

public class Group {

    ...

    @Reference
    List<User> members;

    ...

}

Question: When calling RequestFactory function getGroup().with("members") will RequestFactory get all members in ONLY 1 DB access ?

Or will Request factory make 3 DB access for each DBRef in Group document in the scenario given above?

Thank you very much in advance.

1

There are 1 best solutions below

0
On

RequestFactory itself doesn't access the DB. What it'll do here is:

  1. call getMembers(), as it was requested by the client through .with("members")
  2. for each entity proxy seen (either in the request or in the response), call its locator's isLive method, or if has no Locator, call the entity's findXxx with its getId() (and check whether null is returned).

The first step depends entirely on Morphia's implementation:

  • because you didn't set lazy = true on your @Reference, it won't matter whether RequestFactory calls getMembers() or not, the members will always be loaded.
  • in any case (either eager or lazy fetching), it will lead to 4 Mongo queries (one to get the Group and another 3 for the members; I don't think Morphia tries to optimize the number of queries to only make 1 query to get all 3 members at a time)

The second step however depends entirely on your code.

Remember that RequestFactory wants you to have a single instance of an entity per HTTP request. As I understand it, Morphia has an EntityCache doing just that, but I suspect it could be bypassed by some methods/queries.