1

I need to update a huge amount of records, that are being updated by an integration.

i have the following code:

private void populateRelatedAssetsFields() {
    System.debug('LicenseTriggerHandler.populateRelatedAssetsFields');

    Set<Id> licenseIdSet = new Set<Id>();
    Map<Id,Id> licenseIdToAccountIdMap = new Map<Id,Id>();

    Map <Id, License__c> oldLicenseMap = (Map <Id, License__c>) Trigger.oldMap;

    for (License__c license_i : (List<License__c>)Trigger.new) {
        if (license_i.Account__c != null && (Trigger.isInsert || (oldLicenseMap.get(license_i.Id).Account__c != license_i.Account__c))) {
            licenseIdSet.add(license_i.Id);
            licenseIdToAccountIdMap.put(license_i.Id,license_i.Account__c);
        }
    }

    List<Asset> assetList = [SELECT Id,AccountId,License__c FROM Asset WHERE License__c IN: licenseIdSet];

    if (!assetList.isEmpty()) {
        for(Asset asset_i : assetList) {
            asset_i.AccountId = licenseIdToAccountIdMap.get(asset_i.License__c);
        }
        system.debug('assetList.size(): ' + assetList);
        Update assetList;
    }
}

UPDATE

There is a limit to the amount of time we allow a trigger to run in one transaction. AssetTrigger runs every time i update 200 records at a time, and i want the AssetTrigger to run once\run in different transactions.

How is it possible?

2
  • You're having a serious X/Y Problem here. You have observed some problem, decided how you want to solve it, then asked about how to pursue that implementation. Please take a step back and describe your root issue.
    – Adrian Larson
    Commented Oct 16, 2019 at 13:43
  • @Adrian Larson Thanks for the comment, i removed the previous question to make it more clear.
    – Dana Griff
    Commented Oct 16, 2019 at 14:50

1 Answer 1

4

You can just use iterator instead. It should work if you do a pattern like the following:

public with sharing class MyBatch implements Database.Batchable<SObject>
{
    final List<SObject> records;
    public MyBatch(List<SObject> records)
    {
        this.records = records;
    }

    public Iterable<SObject> start(Database.BatchableContext context)
    {
        return records;
    }

    // remaining implementation
}
4
  • so in execute i can just add update records; and thats it?
    – Dana Griff
    Commented Oct 15, 2019 at 17:38
  • Yeah...you might need the batch to be stateful also.
    – Adrian Larson
    Commented Oct 15, 2019 at 18:03
  • why is stateful needed?
    – Dana Griff
    Commented Oct 16, 2019 at 7:38
  • The problem im having is that the AssetTrigger runs every time i update 200 records at a time, and i want the AssetTrigger to run once\run in different transactions.
    – Dana Griff
    Commented Oct 16, 2019 at 8:30

You must log in to answer this question.

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