Andres’ Tech Blog

Focusing on java technologies.

Objectify’s OnLoad Can Be Tricky

When creating a Ref<?> to another object can be tricky since, here is the scenario:

I have an Entity UserPost that has a reference to UserProfile like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@Entity
public class UserPost {
    @Id
    public Long id;

    @JsonIgnore
    @Index
    @Load(All.class)
    private Ref<UserProfile> user;

    @Ignore
    public String userNickname;

    @OnLoad
    public void onLoad(){
        if(user!=null){
            UserProfile userProfile = user.get();
            if (userProfile != null) {
                this.userNickname = userProfile.userNickname;
            }
        }
    }
  
  public void setUserRef(Ref<UserProfile> userRef) {
        this.user = userRef;
    }

    public static class All {
    }

The problem then was that userNickname was null sometimes even when user was being set. After some trial and error I found this post Google Groups where they mention the fact that @OnLoad only gets called when the Entity is not found in the session.

My solution: call onLoad directly when setting the reference. That makes that instance to be usable right away. But at the same it will be loaded when needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Entity
public class UserPost {
    @Id
    public Long id;

    @JsonIgnore
    @Index
    @Load(All.class)
    private Ref<UserProfile> user;

    @Ignore
    public String userNickname;

    @OnLoad
    public void onLoad(){
        if(user!=null){
            UserProfile userProfile = user.get();
            if (userProfile != null) {
                this.userNickname = userProfile.userNickname;
            }
        }
    }
  
  public void setUserRef(Ref<UserProfile> userRef) {
        this.user = userRef;
      onLoad();
    }

    public static class All {
    }