views:

149

answers:

2

Is google app engine datastore support unique constraints?

Thanks in advance

+4  A: 

Not really, but keys are guaranteed to be unique and you can set the key of your entity to be an arbitrary string. You can take advantage of this to create a unique key when you save your entity to the data store. For example,

public class Entity implements Serializable {

    @Id String id;

    String unique_together_1;
    String unique_together_1;

    public Entity (String unique_together_1, String unique_together_2) {
        this.id = unique_together_1 + "-" + unique_together_2;

                this.unique_together_1 = unique_together_1;
                this.unique_together_2 = unique_together_2;
    }

Obviously this won't work if the unique fields of your entity change later or if you need multiple unique constraints for a single entity type.

This is a good idea. If you do this, when you put() an object which shares `unique_together1` and `unique_together_2` then it will simply overwrite any existing object in the datastore. You might want to use transactions to check to see if its key is already in the datastore and then add it if it isn't.
David Underhill