I want to ensure that only one entity is created for an entity with a specific ancestor Key. My solution is to put the ancestor query inside a transaction, check if the entity exists, and if not, create it.
Will this ensure only one entity exists with a specific ancestor key?
ofy().transact(new VoidWork() {
public void vrun() {
Entity entity = ofy().load().type(Entity.class)
.ancestor(ancestorKey)
.first()
.now();
if (entity == null) {
// Entity does not exist. Create it.
final Entity newEntity = new Entity(ancestorKey);
ofy().save().entity(newEntity).now();
} else {
// Entity already exists.
}
}
}
});
SO doesn't like one-word answers so I can't just say "Yes".
If you're just trying to ensure that one and only one thing exists, you don't need the ancestor query - just do a get-by-key on a known id.
And since Java7 is gone, no reason not to put this in a lambda.