In a Google App Engine app, I have this model:
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Message {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
@Persistent
private Date timestamp;
@Persistent
private String text;
@Unowned
@Persistent(defaultFetchGroup = "true")
private User sender;
...
}
The model has an @Unowned relation to a sender, since a user can exist independently of a message.
What I want to do is persist Message objects with partial User objects (e.g. I'm only interested in storing the user id and username). In my endpoint class I'm storing messages just fine, however, if I don't include all fields for the given user in the relationship, the user object is updated with the fields missing (e.g. user in question no longer has a password etc.). What is the best way of achieving what I want, without 'corrupting' the original object?
PS
My endpoints method is dead simple. Basically just calling pm.makePersistent(message); on the message (given as a method parameter).
You are using the
@Unownedannotation which means that only a reference to the actualUserentity will be stored in thesendervariable under yourMessageclass.When you access the
sendervariable, the Datastore will execute a get query to retrieve theUserentity that is linked to the message.You can confirm this for yourself by navigating to your project's Datastore dashboard (https://console.cloud.google.com/datastore for production, and http://localhost:8080/_ah/admin for local) and browsing the
Messageentities.You should see the field where the
Useris stored named something likeuser_id_OIDwith a value ofKey(User/XXXXX).As a side note, Google recommends moving away from JDO/JPA to Objectify or the Datastore API.
See here: https://cloud.google.com/appengine/docs/java/datastore/jdo/overview-dn2