Wiki source code of Count To-Many Objects without Loading
Last modified by Jonathan 'Wolf' Rentzsch on 2008/11/24 12:35
Show last authors
| author | version | line-number | content |
|---|---|---|---|
| 1 | 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: | ||
| 2 | |||
| 3 | {{code}} | ||
| 4 | |||
| 5 | public Number count${relationship.capitalizedName}() { | ||
| 6 | return countForRelationship("${relationship.name}"); | ||
| 7 | } | ||
| 8 | |||
| 9 | public EOQualifier qualifierFor${relationship.capitalizedName}() { | ||
| 10 | return qualifierForRelationshipWithKey("${relationship.name}"); | ||
| 11 | } | ||
| 12 | |||
| 13 | {{/code}} | ||
| 14 | |||
| 15 | 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: | ||
| 16 | |||
| 17 | {{code}} | ||
| 18 | |||
| 19 | public EOQualifier qualifierForRelationshipWithKey(String aKey) | ||
| 20 | { | ||
| 21 | this.willRead(); | ||
| 22 | |||
| 23 | if ((aKey != null)) | ||
| 24 | { | ||
| 25 | String anEntityName = this.entityName(); | ||
| 26 | EOEntity anEntity = EOModelGroup.defaultGroup().entityNamed(anEntityName); | ||
| 27 | EORelationship aRelationship = anEntity.relationshipNamed(aKey); | ||
| 28 | |||
| 29 | if (aRelationship != null) | ||
| 30 | { | ||
| 31 | EOEditingContext anEditingContext = this.editingContext(); | ||
| 32 | EOGlobalID aGlobalID = anEditingContext.globalIDForObject(this); | ||
| 33 | String aModelName = anEntity.model().name(); | ||
| 34 | EODatabaseContext aDatabaseContext = EOUtilities.databaseContextForModelNamed(anEditingContext, | ||
| 35 | aModelName); | ||
| 36 | aDatabaseContext.lock(); | ||
| 37 | NSDictionary aRow = aDatabaseContext.snapshotForGlobalID(aGlobalID); | ||
| 38 | aDatabaseContext.unlock(); | ||
| 39 | EOQualifier aQualifier = aRelationship.qualifierWithSourceRow(aRow); | ||
| 40 | |||
| 41 | return aQualifier; | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | return null; | ||
| 46 | } | ||
| 47 | |||
| 48 | /** | ||
| 49 | * Return count for the given relationship. | ||
| 50 | */ | ||
| 51 | public Integer countForRelationship(String key) | ||
| 52 | { | ||
| 53 | EOQualifier qual = qualifierForRelationshipWithKey(key); | ||
| 54 | if (qual != null) | ||
| 55 | { | ||
| 56 | String anEntityName = this.entityName(); | ||
| 57 | EOEntity anEntity = EOModelGroup.defaultGroup().entityNamed(anEntityName); | ||
| 58 | EORelationship aRelationship = anEntity.relationshipNamed(key); | ||
| 59 | return ERXEOControlUtilities.objectCountWithQualifier(this.editingContext(), aRelationship | ||
| 60 | .destinationEntity().name(), qual); | ||
| 61 | } | ||
| 62 | return null; | ||
| 63 | |||
| 64 | } | ||
| 65 | |||
| 66 | {{/code}} |