如何使用Java确定Google AppEngine数据存储区中给定键的对象是否存在?

我正在尝试将Sharding Counters示例(code.google.com/appengine/articles/sharding_counters.html)移植到
Java.唯一的问题是
Java API没有类似于
Python的’get_by_key_name’的调用.这是基本的想法:

            Transaction tx = pm.currentTransaction();
            Key key = KeyFactory.createKey(CounterShard.class.getSimpleName(), counter + randomIndex);
            CounterShard shard = pm.getObjectById(CounterShard.class, key);
            if (shard == null) {  // API does not work this way...
                shard = new CounterShard(key, counter);
            }
            shard.increment();
            pm.makePersistent(shard);
            tx.commit();

不幸的是,这会在我第一次运行时抛出JDOObjectNotFoundException.我可以运行一个查询来确定是否存在给定名称的计数器,但这不是事务性的.另一个线程可以做同样的事情,最后两个线程都会创建一个具有相同键的对象.

据我所知,事务中支持的唯一操作(对于Java API)是get和put.那么如何通过尚不存在的键锁定一个对象(即没有’get’)并确保我是第一个也是唯一一个创建它的人?

最佳答案 在这里查看演示代码

http://code.google.com/p/googleappengine/source/browse/trunk/java/demos/shardedcounter/README

点赞