I have a trigger which performs an insert operation.One record count is more than 10k.So,Its giving this exception.I have tried batch apex and future method.Its is not working.Any help will be appreciated!
trigger:
trigger trgInsertRecord on Custom_object__c(after insert,after update)
{
Set<Id> clientIds = new Set<Id>();
for(Custom_object__c c:Trigger.new) {
clientIds.add(c.Client__c);
if(trigger.Isinsert) {
Database.executeBatch(new BatchableClass(clientIds));
}
}
}
batchable class:
global class BatchableClass implements Database.Batchable<sObject> {
Set<Id> clientIds = new Set<Id>();
global BatchableClass(Set<Id> clientIdSet) {
clientIds = clientIdSet;
}
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([Select Id,Client__c from Custom_object__c where Client__c IN:clientIds ]);
}
global void execute(Database.BatchableContext BC, List<Custom_object__c> scope) {
if (scope.isEmpty())
return;
for(Custom_object__c c:scope) {
clientIds.add(c.Client__c);
//some logic to get objlist
insert objlist;
}
}
}
global void finish(Database.BatchableContext BC) {}
}
Best Answer
You have 2 Main issues:
1)
You are executing the same batch for as many items are in your trigger.
You only want to execute the batch once.
2)
It's essentially the same problem again in your batch:
You need to do your work in bulk.