You need to sign in to do that
Don't have an account?
How to Insert 500,000 records through Apex Class - Batch Apex?
My objective is to insert 500,000 records in ObjectA__c created by looping through Prooduct2 (1,000 records) and Area__c (500 records) objects.
My code below runs fine on for a small sample of the records, however I hit governor limits when trying to executive all records.
I been reading on batch apex thinking it may solve my problem, however having never used batch apex, I am not sure if I can pass in the two Objects I need to create the records for the ObjectA__c inserts based on the examples. If I can, can someone please provide an example on how?
If not any suggestions or examples on how to solve this problem would be greatly appreciated?
Thanks in advance
public class RefreshAllObjectARelationships { Public pagereference doRefreshAllObjectARelationships() { List<ObjectA__c> deleteObjectA_records = [SELECT ID FROM ObjectA__c]; System.Debug('DEBUG: deleteObjectA_records List Size =' + deleteObjectA_records.size()); DELETE deleteObjectA_records; List<Product2> products = [SELECT ID, Name FROM Product2]; //1000 Products returned from Query System.Debug('DEBUG: products List Size = ' + products.size()); List<Area__c> Areas = [SELECT ID, Name FROM Area__c]; //500 ObjectA records returned from Query System.Debug('DEBUG: Areas List Size = ' + Areas.size()); List<ObjectA__c> ObjectARelationships = new List<ObjectA__c>(); for(Product2 prod : products){ integer i = 0; for(Area__c A: Areas){ i++; ObjectA__c ObjA_record = new ObjectA__c(Area__c = A.ID, Service_Task__c = prod.ID); if(i>10){ i=0; InsertObjectA_records (ObjectARelationships); ObjectARelationships.Clear(); } ObjectARelationships.add(ObjA_record); } } InsertObjectA_records (ObjectARelationships); RETURN NULL; } public void InsertObjectA_records(List<ObjectA__c> insertObjA_recordList){ System.Debug('DEBUG: ObjA_record List size = ' + insertObjA_recordList.size()); INSERT insertObjA_recordList; System.Debug('DEBUG: ObjA_record records inserted'); insertObjA_recordList.clear(); }
You should use Bulk insert, take a look at the guide:
Bulk API Guide