Monday, 2 January 2012

Simple Property Retrieval/Storage with Google App Engine

After trying a few of the examples for storage in GAE I think that the simplest mechanism is as follows
First, create a key for your application data:
Key appDataKey = KeyFactory.createKey("AppData", "MyApp");

AppData and MyApp aren't fixed - change them according to your needs.

Saving a property:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    
Entity invoiceEntity = new Entity(appDataKey);
invoiceEntity.setProperty("", );
datastore.put(invoiceEntity);


Reading a property:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
try {
    Entity appData = datastore.get(appDataKey);
    return ((Long) appData.getProperty("")).intValue();
} catch (EntityNotFoundException notFoundException) {
    // handle the exception
}

In this case my property is a Long, but it can be any Object. You'll need to cast accordingly.
Note that for my purposes I don't need to worry about either load or concurrency, so the above example may not be suitable for all use cases, but it was the simplest option for me.

1 comment: