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.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete