A Selector class, like the Domain class, utilizes inheritance to gain some standard functionality; in this case, the base class delivered through the FinancialForce.com Enterprise Apex Patterns library, fflib_SObjectSelector
.
A basic example is as follows:
public class RacesSelector extends fflib_SObjectSelector { public List<Schema.SObjectField> getSObjectFieldList() { return new List<Schema.SObjectField> { Race__c.Id, Race__c.Name, Race__c.Status__c, Race__c.Season__c, Race__c.FastestLapBy__c, Race__c.PollPositionLapTime__c, Race__c.TotalDNFs__c }; } public Schema.SObjectTypegetSObjectType() { return Race__c.sObjectType; } }
The base class uses Dynamic SOQL to implement the features described in this chapter. One potential disadvantage this can bring is that references to the fields are made without the Apex compiler knowing about them, and as such, when you attempt to delete or rename fields, no warning is given that the given field is already referenced. To avoid this, the SObjectField
reference to the field is used, which is obtained by stating the SObject name followed by the field name separated by a period. This is somewhat like a static property on the SObject type. This approach ensures that the platform knows the class is referencing the fields, even though they are being used in a dynamic SOQL context.
With this minimal example, the following standard query can be made by leveraging the selectSObjectsById
base class method. This method takes the information provided by the preceding methods and constructs a SOQL query dynamically and executes it via Database.executeQuery
:
List<Race__c> races = (List<Race__c>)
new RacesSelector().selectSObjectsById(raceIds);
Note that the fflib_SObjectSelector.selectSObjectsById
base class method performs a number of features, described later in this chapter. Also, note that an instance of the Selector was created but was not actually stored using an instance permits base class behavior to be inherited. Additional benefits of using instances of Selectors are covered later in this chapter when we discuss Selector factories and testing.
The preceding Selector method example dynamically creates the following SOQL. As we progress through this chapter, how this is done will become more clear:
SELECT Name, TotalDNFs__c, Status__c, Season__c, Id, PollPositionLapTime__c, FastestLapBy__c FROM Race__c WHERE id in :idSet ORDER BY Name
The following table shows some of the key base class methods of the fflib_SObjectSelector
class available to your Selector methods and also those that can be overridden. Note that the getSObjectType
and getSObjectFieldList
methods are abstract and thus must be implemented as minimum, as per the previous example.
The following sections describe these methods in further detail. Do also take some further time to explore further methods and associated code comments in the base class code.
3.138.117.75