Wednesday, April 7, 2010

Unique constraint on App Engine Datastore

Another challenge I faced on GAE Datastore is inability to use unique constraints. Sometimes it is absolutely needed to have such constraints and this is my case.

Following solution is not universal but it will help in many cases. Idea is to create entity primary key based on field(s) that should be unique.

Consider following example:
public class Link implements Serializable {
    private Key key;
    private String parentId;
    private String childId;
    //getters and setters
}
It is needed to force that only one link exist for given pair (parent, child) and it can be done in the following way:
@PersistenceCapable
public class Link implements Serializable, StoreCallback {
    @Persistent
    @PrimaryKey
    private Key key;
    private String parentId;
    private String childId;
    //getters and setters
    @Override
    public void jdoPreStore() {
        key = KeyFactory.createKey(Link.class.getSimpleName(), parentId + "::" + childId);
    }
}
Of course any divider can be used instead of "::". Actually there are slightly more complex rules to ensure that generated string is uniquely identifies parentId and childId pair but it is unrelated to topic.

No comments:

Post a Comment