我正在使用 Google App Engine 编写系统代码,并且只有当对象尚不存在时我才需要将其放入数据存储区。我可以使用 datastore.put()
方法,但我需要知道该对象是否已经存在以计算我拥有的新对象的数量。
据我所知,我有以下选项(假设我有键作为属性和实体键):
private Entity getEntity(String key)
{
DatastoreService datastore =
DatastoreServiceFactory.getDatastoreService();
// Build a query to select this entity from the database:
Query q = new Query("MyEntity");
q.setKeysOnly();
// Add a filter for the key attribute:
q.addFilter("key", Query.FilterOperator.EQUAL, key);
PreparedQuery pq = datastore.prepare(q);
// Select a single entity from the database
// (there should be no more than one matching row anyway):
List<Entity> list = pq.asList(FetchOptions.Builder.withLimit(1));
if (!list.isEmpty())
// Return the found entity:
return list.get(0);
else
return null;
}
或
private Entity getEntity(String key)
{
DatastoreService datastore =
DatastoreServiceFactory.getDatastoreService();
// Get a key that matches this entity:
Key key = KeyFactory.createKey("MyEntity", key);
try {
return datastore.get(key);
} catch (EntityNotFoundException e) {
// Entity does not exist in DB:
return null;
}
}
我倾向于使用第二个,因为它看起来更直接,但我担心它可能不应该以这种方式使用,因为它会引发异常,并且可能会产生开销。
哪种方法更适合检查数据库中是否存在实体?
有更好的方法吗?
最佳答案
除非您的实体很大并且具有许多属性,否则执行获取会更快 - 在这种情况下,仅键查询可能会更快。如果性能可能是这里的一个重要问题,我会建议进行基准测试 - 但如果不是,后一种方法更直接。
关于java - Google App Engine 性能 - 检查对象是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6693329/