Thursday, December 20, 2012

sObject in Apex Programming Language

In our article, Overview of Apex Programming Language, we learnt that Apex is data focused and programming in Apex is like writing stored procedures in a database. The very important element of the language which makes the integration with the database very easy to use is sObject. We briefly looked at it in our previous article, Data Types in Apex. Let us have a detailed look in this article.

sObject represents an Object in Force.com platform. We know that each object in Force.com platform, standard or customized, is just like a table in the database. sObject data type in Apex corresponds to these database objects. In other words, it is an object that can be stored in the Force.com platform database.


The following example creates an empty Account Object and assigns it to sObject. As you can see, it is just like instantiating a class.


    sObject s = new Account();
Instead of the generic sObject, you could instantiate it with specific type Account which is an sObject as well. 

    Account a = new Account();
You can instantiate the object with initial values or assign the value after instantiating it like below.

    Account a = new Account(Name='ABC Corp');
The above statement is same as the following 2 statements,

    Account a = new Account();
    a.Name = 'ABC Corp';

You can retrieve an sObject using Salesforce Object Query Language (SOQL) and Salesforce Object Search Language (SOSL). You also use sObject while executing Data Manipulation Language (DML). We will sure explore all the three - SOQL, SOSL and DML in detail in future articles. 


The following example uses SOQL to retrieve an sObject -
    Account a = [SELECT Id, Name, Description FROM Account WHERE Name='ABC Corp'];
You can then read the individual field values using the dot notation like a.Id, a.Name or a.Description.

You can retrieve an array of sObject as below -

    Account[] a = [SELECT Id, Name, Description FROM Account]; 
Another specialty of sObject is using an sObject, you can get related parent and child sObjects and access their fields. We will explore this one as well in detail in one of our future articles.


Happy cloud computing using Salesforce!

No comments:

Post a Comment