Objectify loads object behind Ref<?> even when @Load is not specified

心已入冬 提交于 2019-12-03 03:41:20

In your example code, you are not specifying @Load which means that loading the account will not fetch the User. However, your @ApiMethod is serializing the account back to the client, so the user property is been accessed, thus a separate fetch is issued to load the user object. That's why you are getting the information of the user when calling the method.

Not specifying @Load doesn't mean that you won't get a User back. It means that you are not going to retrieve a User unless you specifically ask for it later.

Ref works like this:

  • I'm a reference, so by default I won't fetch the data.
  • If you ask for me, then I will first load the data, then answer you.
  • Oh, if you tell me to @Load myself, then I will fetch the data initially and have it ready for you.

So this is working fine in your code... but then your @ApiMethod is serializing your Account object back to the client. The serialization process is going through every property in your Account object, including the user property. At this point, the Ref<User> is being accessed, so the data will get fetched from the Datastore and then returned to the client.

This is making your code very inefficient, since the Account objects are loaded without the User information, but then you always access the User info later (during serialization), issuing a separate fetch. Batching gets from the Datastore is way more efficient than issuing separate gets.

In your case, you can do either of two things:

  1. Add @Load to the user property, so the Account object is fetched efficiently.
  2. Make your @ApiMethod return a different Account object without the user property (thus avoiding fetching the user if you don't need it).

Option 2 above is quite useful since you can abstract your internal Datastore structure from what the client sees. You'll find yourself using this patter quite often.

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