It took me a little bit to figure out what was going on because in the
datastore the key property is __key__ so if you query using the
Datastore Viewer you would do something like:
select __key__ from Something
but when using JDO you've got to use the attribute name of the key
field and JDO will map it to __key__
Ok, so what I've done is to have all my datastore classes inherit from
my own abstract Entity class where I've defined the following:
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName="datanucleus", key="gae.encoded-pk",
value="true")
private String ek; // some use encodedKey for this name, but I
keep them short to save datastore space
@Persistent
@Extension(vendorName="datanucleus", key="gae.pk-name",
value="true")
private String id;
Then I wrote this utility method which works for any class that I want
to check to see if a key already exists:
public static boolean doesEntityExist(Class<? extends Entity>
entityClass, String id) {
PersistenceManager pm = null;
try {
pm = PMF.getPersistenceManager();
String idKeyString =
KeyFactory.createKeyString(entityClass.getSimpleName(), id);
Query q = pm.newQuery("select ek from " + entityClass.getName()
+
" where ek = '" + idKeyString + "'");
List<?> keys = (List<?>)q.execute();
return keys.size() > 0;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (pm != null) pm.close();
}
}
So, if this is in a class called Utility and you have an entity class
Employee and you want to check for an unencoded key string of
"EMP-1234" just call it like this:
if (Utility.doesEntityExist(Employee.class, "EMP-1234")) {
// entity with key already exists
}
Let me know if this helps,
Stephen