开发者

How to enforce unique field value in java Google App Engine

开发者 https://www.devze.com 2022-12-08 05:25 出处:网络
I am try to find out how to enforce uniqueness in fields other than the unique id. Example: @PersistenceCapable(identityType = IdentityType.APPLICATION)

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 u开发者_开发问答nique as well
}

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

Daniel


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.


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/


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消