function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Steve Berley [Left Propeller]Steve Berley [Left Propeller] 

too many dml rows error when using implementing database.stateful

I have a batch class that implements database.stateful so global values are visible across batches.  I then save the data in the finish method.

All worked fine until there was enough data involved that the save is now generating a Too Many DML rows error. 

I could use some guidance about a pattern to use to get around this issue as changing the batch size won't matter since the save needs to be in the finish method.

I realize this is a simplistic approach, but could I do something as basic as breaking the list to be saved into multiple lists then inserting them with separate commands but within the same context?
 
global class batchClass implements Database.Batchable<sObject>, database.stateful {

	global map<id, sobject> dataStruct;
        global string q = 'select whatever from sObject';

	global Database.QueryLocator start(Database.BatchableContext BC) {
		dataStruct = map<id, sobject>();
		return Database.getQueryLocator(q);
	}

   	global void execute(Database.BatchableContext BC, list<Item__History> scope) {
		dataStruct = batchClass_tools.processScope(scope, dataStruct);
	}

	global void finish(Database.BatchableContext BC) {
        insert dataStruct.values();
	}
}

 
Raj VakatiRaj Vakati
The Issue is you are trying to insert all the records in the final method and your batch is stateful so all the variable will not be reset .  which will be executed once in the batch lifecycle .. that is causing an issue 

And Your dataStruct is contained all the records 


Perform your DML in execute method as shown below 

 
global class batchClass implements Database.Batchable<sObject>, database.stateful {

	global map<id, sobject> dataStruct;
        global string q = 'select whatever from sObject';
global Integer totalVals = 0 ; 
	global Database.QueryLocator start(Database.BatchableContext BC) {
		dataStruct = map<id, sobject>();
		return Database.getQueryLocator(q);
	}

   	global void execute(Database.BatchableContext BC, list<Item__History> scope) {
		dataStruct = batchClass_tools.processScope(scope, dataStruct);
		     insert dataStruct.values();
			 totalVals = totalVals+dataStruct.size() ; 
	
	}

	global void finish(Database.BatchableContext BC) {
		System.debug('Total Records'+dataStruct);
   }
}