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