[SalesForce] Batch Apex – System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

I am getting

System.CalloutException: You have uncommitted work pending. Please
commit or rollback before calling out.

global class BatchClassName implements Database.Batchable<`string`>,
                                       Database.Stateful, 
                                       Database.AllowsCallouts {

    //Local Variables
    global list<string> lstTeamAssignedOfficerId;
    global final list<string> lstAccountOfficerId;

    global <BatchClassName_Constructor>(list<string> lstAccountOfficer) {
        this.lstAccountOfficerId = new list<string>();
        this.lstAccountOfficerId = lstAccountOfficer;
    }

    global Iterable<string> start(Database.BatchableContext ctx) {
        return lstAccountOfficerId;
    }

    global void execute(Database.BatchableContext ctx, list<string> lstAccountOfficer) {
        /*Performing All SOQL and DML operations - No Callouts performed*/
    }

    global void finish(Database.BatchableContext ctx) {
        /*Performing Callout */        
    }
}

I think Finish method will execute after the all the Batches are completed and data is commit in objects. I have written code in past to perform callout in Finish Method and DML operations in execute method.

Best Answer

I Identified the issue in Batch Class code. There was a DML operation between callouts which was causing this.

Thanks for your help @Eric.

believe since you are implementing database.stateful that the DML persits and thus you cannot make a callout in the finish method

Database.stateful is to persist values of instance variables and not for DML operations. Issue was in Finish method code, while doing 4 difffenent APEX callouts code was inserting records(DML) inbetween callouts. I just moved all the DML statements after callouts to resolve the issue.

Related Topic