0

I am writing code that calls an API to get external client info. I'm at the point where I have it working but I am wondering if there is a more efficient way to save the data to the Account object. Right now I am iterating through the list I have and updating each account but I am hitting governor limits pretty easily:

     List<ParseAdminResponse> acctList = ParseAdminResponse.parse(response.getBody());
        for(Integer i = 0; i < acctList.size(); i++){
         if(acctList[i].Success = true){
          acctId = acctList[i].SfAccountId;
          version = acctList[i].ClientVersion;
          Date todaysDate = system.today();
          // Query for the account
            Account queriedAccount = [SELECT Version__c 
                          FROM Account 
                          WHERE id = :acctId];

          // Update the account's version
          queriedAccount.Version__c = version;
          queriedAccount.Last_Admin_Check__c = todaysDate;
          update queriedAccount;

          } else{
          system.debug(acctList[i].ErrorMessage); 
          }
        }

Is there a better way than saving the results I get one at a time?

2
  • As an aside, watch out for Boolean value; if(value = true); this is an assignment, and will result in the if statement always being true (and value would be set to true). The code should be if(acctList[i].Success == true). or even just if(acctList[i].Success), because Boolean values are already Boolean values.
    – sfdcfox
    Commented Mar 26, 2020 at 15:57
  • Thank you for the explanation! Commented Mar 26, 2020 at 16:12

1 Answer 1

1

You don't need to query the records first, unless you needed to lock them. You can just construct the records in memory and update:

Date todaysDate = system.today();
Map<Id, Account> accounts = new Map<Id, Account>();
for(ParseAdminResponse par: acctList) {
    if(par.Success) {
        accounts.put(par.SfAccountId, new Account(Id=par.SfAccountId, Version__c=par.ClientVersion, Last_Admin_Check__c=todaysDate));
    }
}
update accounts.values();

If you really wanted to lock the records first:

Date todaysDate = system.today();
Map<Id, Account> accounts = new Map<Id, Account>();
for(ParseAdminResponse par: acctList) {
    if(par.Success) {
        accounts.put(par.SfAccountId, new Account(Id=par.SfAccountId, Version__c=par.ClientVersion, Last_Admin_Check__c=todaysDate));
    }
}
Account[] locks = [SELECT Id FROM Account WHERE Id = :accounts.keySet() FOR UPDATE];
update accounts.values();
1
  • Thank you for the explanation and answer, this worked perfectly. Commented Mar 26, 2020 at 16:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .