Excluding properties when persisting unowned entity relation jdo (gae)

46 Views Asked by At

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).

1

There are 1 best solutions below

7
Brett On

You are using the @Unowned annotation which means that only a reference to the actual User entity will be stored in the sender variable under your Message class.

When you access the sender variable, the Datastore will execute a get query to retrieve the User entity 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 Message entities.

You should see the field where the User is stored named something like user_id_OID with a value of Key(User/XXXXX).

As a side note, Google recommends moving away from JDO/JPA to Objectify or the Datastore API.

Warning: We think most developers will have a better experience using the low-level Datastore API, or one of the open-source APIs developed specifically for Datastore, such as Objectify. JDO was designed for use with traditional relational databases, and so has no way to explicitly represent some of the aspects of Datastore that make it different from relational databases, such as entity groups and ancestor queries. This can lead to subtle issues that are difficult to understand and fix.

See here: https://cloud.google.com/appengine/docs/java/datastore/jdo/overview-dn2