@SuppressWarnings("unchecked")
public static EOEnterpriseObject objectWithPrimaryKeyValue(EOEditingContext ec,
String entityName,
Object primaryKeyValue,
NSArray prefetchingKeyPaths, boolean refreshRefetchedObjects, boolean throwIfMissing) {
EOEntity entity = EOUtilities.entityNamed(ec, entityName);
NSDictionary<String, Object> values;
if(primaryKeyValue instanceof NSDictionary) {
values = (NSDictionary<String, Object>)primaryKeyValue;
} else {
if (entity.primaryKeyAttributes().count() != 1) {
throw new IllegalStateException("The entity '" + entity.name() + "' has a compound primary key and cannot be used with a single primary key value.");
}
values = new NSDictionary<String, Object>(primaryKeyValue, entity.primaryKeyAttributeNames().lastObject());
}
NSArray eos;
if (prefetchingKeyPaths == null && !refreshRefetchedObjects) {
EOGlobalID gid = entity.globalIDForRow(values);
EOEnterpriseObject eo = ec.faultForGlobalID(gid, ec);
if (throwIfMissing) {
eo.willRead();
}
eos = new NSArray<EOEnterpriseObject>(eo);
}
else {
EOQualifier qualfier = EOQualifier.qualifierToMatchAllValues(values);
EOFetchSpecification fs = new EOFetchSpecification(entityName, qualfier, null);
// Might as well get fresh stuff
fs.setRefreshesRefetchedObjects(refreshRefetchedObjects);
if (prefetchingKeyPaths != null) {
fs.setPrefetchingRelationshipKeyPaths(prefetchingKeyPaths);
}
eos = ec.objectsWithFetchSpecification(fs);
}
if (eos.count() > 1) {
throw new MoreThanOneException("Found multiple objects for the entity '" + entity.name() + "' with primary key value: " + primaryKeyValue);
}
if (eos.count() == 0) {
if (throwIfMissing) {
throw new EOObjectNotAvailableException("There was no '" + entity.name() + "' found with the id '" + primaryKeyValue + "'.");
}
return null;
}
return (EOEnterpriseObject)eos.lastObject();
}