Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enforce unique field value in java Google App Engine

I am try to find out how to enforce uniqueness in fields other than the unique id.

Example:

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class User implements IsSerializable {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    private String name; 

    @Persistent
    private String email; // <= I want this to be unique as well
}

In the example above, how can I enforce uniqueness of the email value across the database?

Daniel

like image 702
supercobra Avatar asked Oct 13 '09 21:10

supercobra


3 Answers

There is currently no built in way using the app engine datastore. See this datanculeus ticket for example. (Note that JDO itself does have a @unique annotation.)

One way to 'fake' it would be to create another kind/class called Email with the email itself as a key, and the User's key as a property. Since the email is now a key, it will be forced to be unique. Just make sure your Email entities are top level entities, not children of their associated User. You'll also have to pay close attention to your use of transactions to make sure you don't let a duplicate slip through the cracks if two users try to use the same email at the same exact time.

like image 72
Peter Recore Avatar answered Nov 09 '22 15:11

Peter Recore


I have written a class that takes care of all the functionality for adding Unique Fields to the App Engine Entities. Please feel free to use it.

Plug this class in your project and simply add get and update methods and provide the Entity Name, Field Name and the unique field value

Source code is available here:

http://code.google.com/p/appengine-uniquefields/

like image 33
xtrahelp.com Avatar answered Nov 09 '22 16:11

xtrahelp.com


This feature is not supported yet. If you decided to write a DAO Layer in your project (Not a bad idea), you can do a query that will test whatever limits you want inside of MyObjectDAO.addMyObject(o) which will throw a MySuperDuplicateValueException.

like image 42
user259349 Avatar answered Nov 09 '22 17:11

user259349