use of com.google.cloud.datastore.DatastoreException in project google-cloud-java by GoogleCloudPlatform.
the class DatastoreSnippets method batchAddEntities.
/**
* Example of adding multiple entities.
*/
// [TARGET add(FullEntity...)]
// [VARIABLE "my_key_name1"]
// [VARIABLE "my_key_name2"]
public void batchAddEntities(String keyName1, String keyName2) {
// [START batchAddEntities]
Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
entityBuilder1.set("propertyName", "value1");
Entity entity1 = entityBuilder1.build();
Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
entityBuilder2.set("propertyName", "value2");
Entity entity2 = entityBuilder2.build();
try {
datastore.add(entity1, entity2);
} catch (DatastoreException ex) {
if ("ALREADY_EXISTS".equals(ex.getReason())) {
// at least one of entity1.getKey() and entity2.getKey() already exists
}
}
// [END batchAddEntities]
}
use of com.google.cloud.datastore.DatastoreException in project google-cloud-java by GoogleCloudPlatform.
the class TransactionSnippets method commit.
/**
* Example of committing a transaction.
*/
// [TARGET commit()]
public Key commit() {
Datastore datastore = transaction.getDatastore();
// [START commit]
// create an entity
KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
Key key = datastore.allocateId(keyFactory.newKey());
Entity entity = Entity.newBuilder(key).set("description", "commit()").build();
// add the entity and commit
try {
transaction.put(entity);
transaction.commit();
} catch (DatastoreException ex) {
// handle exception
}
return key;
}
use of com.google.cloud.datastore.DatastoreException in project google-cloud-java by GoogleCloudPlatform.
the class ITDatastoreTest method testUpdate.
@Test
public void testUpdate() {
List<Entity> keys = DATASTORE.fetch(ENTITY1.getKey(), ENTITY3.getKey());
assertEquals(ENTITY1, keys.get(0));
assertNull(keys.get(1));
assertEquals(2, keys.size());
try {
DATASTORE.update(ENTITY3);
fail("Expecting a failure");
} catch (DatastoreException expected) {
// expected;
}
DATASTORE.add(ENTITY3);
assertEquals(ENTITY3, DATASTORE.get(ENTITY3.getKey()));
Entity entity3 = Entity.newBuilder(ENTITY3).clear().set("bla", new NullValue()).build();
assertNotEquals(ENTITY3, entity3);
DATASTORE.update(entity3);
assertEquals(entity3, DATASTORE.get(ENTITY3.getKey()));
}
Aggregations