1
votes

I have a entity relation in my application using the @Parent annotation to form entity groups.

https://code.google.com/p/objectify-appengine/wiki/Entities#@Parent_Relationships

import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Parent;

@Entity
public class Person {
    @Id Long id;
    String name;
}

@Entity
public class Car {
    @Parent Key<Person> owner;
    @Id Long id;
    String color;
}

I am using Google Cloud Endpoints to create a RESTFul service. I would like to create a GET in my resource that returns the JSON for not only the parent but for the entire entity group. What's a good way to do this?

What I have right now is this ...

@ApiMethod(
    name = "persons.get",
    httpMethod = HttpMethod.GET,
    path = "persons/{id}"
 )
public Person get(@Named("id") String webSafeKey) {

    Key<Person> key = Key.create(webSafeKey);
    Person person= ofy().load().key(key).safe();

    return person;

}

This returns the JSON for person, but what if I want in to include the JSON for the person's cars. Maybe something like getters and setters getCars() in the person Object. I was wondering if there was something better though.

-- UPDATE --

Also, there doesn't seem to be a good way to return objects in the getters and setters that aren't literal nor convert to JSON without adapters.

2

2 Answers

1
votes

What about having the car id in person object and load it as well when loading the person object.

@Entity
public class Person {
    @Id Long id;
    String name;
    Ref<Car> car;
}

@Entity
public class Car {
    @Parent Key<Person> owner;
    @Id Long id;
    String color;
}
public Person get(@Named("id") String webSafeKey) {

    Key<Person> key = Key.create(webSafeKey);
    Person person= ofy().load().key(key).safe();
    return person;

}

And from person object, you can access the car by

Car car = person.car.get();
0
votes

Personally, I found that the endpoints way of doing things only got me so far. I also needed a way to send/receive arbitrary groups of entities. So, I created a pair of endpoints for sending/receiving a class like this:

public class DataParcel implements Serializable {
  public Integer operation = -1;
  private static final long serialVersionUID = 1L;
  public List<String> objects = null;   // new ArrayList<String>();
}

The objects are JSON'ed instances of any of my entities. So for your situation, your 'get' method could return a DataParcel; your implementation would load a Person and any number of Cars into a DataParcel instance and return it to the client.

(The Serializable is unrelated to your question - it allows me to put it in a TaskQueue for later processing.)