[SalesForce] Too many DML rows: 10001

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)

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)); 
             }      
        }
 }

You are executing the same batch for as many items are in your trigger.

trigger trgInsertRecord on Custom_object__c(after insert,after update) 
{
  if (Trigger.isInsert)
  {
    Set<Id> clientIds = new Set<Id>();
    for(Custom_object__c c:Trigger.new)
    {
      clientIds.add(c.Client__c);    
    }
    if (!clientIds.isEmpty())
    Database.executeBatch(new BatchableClass(clientIds));
  }
}

You only want to execute the batch once.

2)

It's essentially the same problem again in your batch:

for(Custom_object__c c:scope) {
            clientIds.add(c.Client__c);  



    //some logic to get objlist       

        insert objlist; 
    }

You need to do your work in bulk.

List<Other_object__c> objs = new List<Other_Object__c>();
for(Custom_Object__c obj: scope)
{
  //some work here
  objs.add(someObj);
}
insert objs;
Related Topic