Create-or-Err with Objectify

后端 未结 1 721
再見小時候
再見小時候 2021-01-16 09:03

I\'m getting started with Google App Engine, and I\'m using Objectify. How do I create a root entity in the data store, but err if it already exists? I didn\'t find anythi

相关标签:
1条回答
  • 2021-01-16 09:31

    This should guarantee consistent behavior:

    final String id = // pick the unique id
    final long txnId = // pick a uuid, timestamp, or even just a random number
    
    ofy().transact(new VoidWork() {
        public void vrun() {
            Thing th = ofy().load().type(thing.class).id(id).now();
            if (th != null) {
                if (th.getTxnId() == txnId)
                    return;
                else
                    throw ThingAlreadyExistsException();
            }
    
            th = createThing(id, txnId);
            ofy().save().entity(th);
        }
    });
    
    0 讨论(0)
提交回复
热议问题