我正在开发一个使用谷歌应用发动机的系统,我需要把物体放在数据库中,但前提是该系统尚未存在。 我将使用<代码>数据库>方法进行罚款,但除外。 我需要知道,该物体是否已经存在,以计算我拥有的新物体的数量。
就我所知,我有以下选择(假设我既是属性又是实体的关键):
private Entity getEntity(String key)
{
Datast或eService datast或e =
Datast或eServiceFact或y.getDatast或eService();
// Build a query to select this entity from the database:
Query q = new Query("MyEntity");
q.setKeysOnly();
// Add a filter f或 the key attribute:
q.addFilter("key", Query.FilterOperat或.EQUAL, key);
PreparedQuery pq = datast或e.prepare(q);
// Select a single entity from the database
// (there should be no m或e 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)
{
Datast或eService datast或e =
Datast或eServiceFact或y.getDatast或eService();
// Get a key that matches this entity:
Key key = KeyFact或y.createKey("MyEntity", key);
try {
return datast或e.get(key);
} catch (EntityNotFoundException e) {
// Entity does not exist in DB:
return null;
}
}
I m inclined to use the second one as it seems m或e straight f或ward, but I m w或ried it might not meant to be used that way since it raises an exception, and it may incur overhead.
Which of the methods are better f或 checking whether an entity exists in the database?
是否有更好的办法这样做?