Count To-Many Objects without Loading

Last modified by Jonathan 'Wolf' Rentzsch on 2008/11/24 12:35

If you want to count the number of objects off a to-many, but without fetching all of them into memory, then add this to your _Entity.java templates inside the to-many section:


public Number count${relationship.capitalizedName}() {
   return countForRelationship("${relationship.name}");
  }

 public EOQualifier qualifierFor${relationship.capitalizedName}() {
   return qualifierForRelationshipWithKey("${relationship.name}");
  }

Then either add this to _Entity.java (lame), or to a generic superclass that you use for all of your EO objects (preferred), add this:


public EOQualifier qualifierForRelationshipWithKey(String aKey)
{
this.willRead();

if ((aKey != null))
{
String anEntityName = this.entityName();
EOEntity anEntity = EOModelGroup.defaultGroup().entityNamed(anEntityName);
EORelationship aRelationship = anEntity.relationshipNamed(aKey);

if (aRelationship != null)
{
EOEditingContext anEditingContext = this.editingContext();
EOGlobalID aGlobalID = anEditingContext.globalIDForObject(this);
String aModelName = anEntity.model().name();
EODatabaseContext aDatabaseContext = EOUtilities.databaseContextForModelNamed(anEditingContext,
       aModelName);
aDatabaseContext.lock();
NSDictionary aRow = aDatabaseContext.snapshotForGlobalID(aGlobalID);
aDatabaseContext.unlock();
EOQualifier aQualifier = aRelationship.qualifierWithSourceRow(aRow);

return aQualifier;
}
}

return null;
}

/**
* Return count for the given relationship.
*/

public Integer countForRelationship(String key)
{
EOQualifier qual = qualifierForRelationshipWithKey(key);
if (qual != null)
{
String anEntityName = this.entityName();
EOEntity anEntity = EOModelGroup.defaultGroup().entityNamed(anEntityName);
EORelationship aRelationship = anEntity.relationshipNamed(key);
return ERXEOControlUtilities.objectCountWithQualifier(this.editingContext(), aRelationship
       .destinationEntity().name(), qual);
}
return null;

}