Posts Tagged ‘Apex caching’

Apex Caching using Salesforce class

Posted: June 30, 2015 by Narendra Shah in Uncategorized
Tags: ,

Untold fact is static variable can be created and used as cached across your transaction. In recursive trigger, we see boolean flag is used to prevent recursive triggers, that is problem solving approach.
But in order to reduce soql, best option is to cache, and use across classes, triggers, controllers in same transaction.
By that way, we can stay away from hitting governance limit.

Sample without Cache:

trigger SoqlTrigger on Account(before insert, after insert, before update,after update) {
List acctsWithOpps =[SELECT Id,(SELECT Id,Name,CloseDate FROM Opportunities) FROM Account WHERE Id IN :Trigger.New];
if (Trigger.isInsert) {
if (Trigger.isBefore) {
//access acctsWithOpps and process
} else if (Trigger.isAfter) {
//access acctsWithOpps and process
}
}
else{
if (Trigger.isBefore) {
//access acctsWithOpps and process
} else if (Trigger.isAfter) {
//access acctsWithOpps and process
}
}
}

Problem with above code is, acctsWithOpps will be called 4 times during transaction. To save this time, we can use following, where same query is called only once.

Sample with Cache():
Account Cache Class Cache:
public class AccountOppsCache {
public static List acctsWithOpps=[SELECT Id,(SELECT Id,Name,CloseDate FROM Opportunities) FROM Account WHERE Id IN :Trigger.New];
}

SoqlTrigger trigger:

trigger SoqlTrigger on Account(before insert, after insert, before update,after update) {
List acctsWithOpps =[SELECT Id,(SELECT Id,Name,CloseDate FROM Opportunities) FROM Account WHERE Id IN :Trigger.New];
if (Trigger.isInsert) {
if (Trigger.isBefore) {
//access AccountOppsCache.acctsWithOpps and process
} else if (Trigger.isAfter) {
//access AccountOppsCacheacctsWithOpps and process
}
}
else{
if (Trigger.isBefore) {
//access AccountOppsCache.acctsWithOpps and process
} else if (Trigger.isAfter) {
//access AccountOppsCache.acctsWithOpps and process
}
}
}