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
Kunal Purohit 4Kunal Purohit 4 

How to insert multiple records in Empty object using batch apex?

I am having custom object Test__c. There is no sigle record in this object.  I want to insert multiple records using batch apex. Plz help.
Best Answer chosen by Kunal Purohit 4
ShirishaShirisha (Salesforce Developers) 
Hi Kunal,

Greetings!

You can use a custom iterator. Here is an example:
 
global class BatchSObjectFeeder implements Iterator<SObject>, Iterable<SObject> {
    SObject[] source;
    
    global Iterator<SObject> iterator() {
        return this;
    }
    
    global BatchSObjectFeeder(SObject[] source) {
        this.source = source;
    }
    
    global SObject next() {
        return source.remove(0);
    }
    
    global boolean hasNext() {
        return source!=null && !source.isempty();
    }
}
 
global class BatchProcessor implements Database.batchable<SObject> {
    SObject[] source;
    
    global BatchProcessor(SObject[] source) {
        this.source = source;
    }

    global Iterable<SObject> start(Database.BatchableContext bc) {
        BatchSObjectFeeder bf = new BatchSObjectFeeder(source);
        return bf;
    }
    
    global void execute(Database.BatchableContext bc, SObject[] scope) {
        insert scope;
    }
    
    global void finish(Database.BatchableContext bc) {
    
    }
}

To use this, simply construct a new BatchProcessor with a list of unsaved records of any size (even millions of records), then run Database.executeBatch with the class. The only limit on the list size will be the heap. You can also use Database.Stateful if you need to record errors elsewhere, or you can catch errors and log them to a separate object used for recording this sort of information.
 
Edit: Note that for efficiency, this passes the list by reference, and that the code is destructive (the list will shrink to nothing as it consumes the data). If you don't want this behavior, implement an index instead.

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri