Wednesday 15 May 2013


Database Records as Objects

All database objects, standard and custom, are available as first-class members of the Apex
language, automatically and transparently.This eliminates the mind-numbing, error-prone
work of importing, mapping, and translating between relational and program data structures,
chores commonly required in general-purpose programming languages. In Apex,
references to database objects are verified at compile time.This reduces the possibility of
runtime surprises caused by field or object mismatches. Listing 5-22 shows an example of
creating a record in the Resource custom database object and setting its name field.

Listing 5-22 Creating a Record
Resource__c resource = new Resource__c();
resource.Name = 'Larry';

Database relationships are also exposed in Apex.The __r syntax refers to a relationship
field, a field that contains a reference to another object or list of objects. Listing 5-23
builds on the previous listing, creating a standard Contact record and associating it with
the Resource record.

Listing 5-23 Creating a Record with Relationship
Contact c = new Contact();
c.FirstName = 'Larry';
resource.Contact__r = c;

The Force.com IDE’s Schema Explorer can take the mystery out of relationship fields
like Contact__r. It displays the correct syntax for referring to fields and relationships,
based on the actual schema of the database object. Its Schema list on the right side displays
all objects, custom and standard. Drilling into an object, the Fields folder lists all fields in
the object and their types.A reference type indicates that a field is the child object in a
Lookup relationship. Expand these fields to reveal their parent object’s type and name. For
example, Contact__r is the foreign key to the Contact object
Data integrity is protected in Apex at compile and runtime using object metadata. For
example, Name is defined as a read-only field in Contact, so the code in Listing 5-24
cannot be compiled.

Listing 5-24 Attempted Assignment to Read-Only Field
Contact c = new Contact();
c.Name = 'Larry';
After a database object is referenced in Apex code, that object cannot be deleted or
edited in a way that invalidates the code.This protects your code from changes to the
database schema. Impacted code must be commented out before the database objects are
modified.

No comments:

Post a Comment