Can we use map function on object instead of list to do bulk DML

apex

Wanted to understand what is more efficient to do bulk insert/updates on records.

Opportunity opportunity = new Opportunity();
for(Id accountId : accountIds) {
  opportunity.put('Name', 'Opportunity ' + accountId);
  opportunity.put('AccountId', accountId);
  opportunity.put('StageName', 'Prospecting');
  opportunity.put('Amount', 0.0);
  opportunity.put('CloseDate', Date.Today().addDays(90));
}

insert opportunity;

OR

List<Opportunity> opportunities = new List<Opportunity>();
for(Id accountId : accountIds) {
  Opportunity opp = new Opportunity();
  opp.Name = 'Opportunity ' + accountId;
  opp.AccountId =  accountId;
  opp.StageName = 'Prospecting';
  opp.Amount = 0.0;
  opp.CloseDate = Date.Today().addDays(90);
  opportunities.add(opp);
}

insert opportunities;

Best Answer

Neither of these examples uses a Map. You can't perform DML on a Map, although if you have, say, a Map<Id, sObject> you can do insert myMap.values();

Your first example is entirely wrong. It will insert exactly one Opportunity with the AccountId set to the last Id in accountIds, which is not what you want.

The second example is correctly bulkified.

Related Topic