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
nilesh walkenilesh walke 

hey guys i am new in apex batch class . now i want to create a account record and hence 1 contact record must be create using batch apex

Here my code  i want code in minimum lines 


public class Demo3 implements Database.Batchable<SObject> {
    public Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator('Select id, name, phone, (select id, name,phone from contacts)from account');
    }
    public void execute(Database.BatchableContext BC,List<Account> Acclist){
        set<id> AccIds = New set<id>();
        for(Account Acc:Acclist){
            AccIds.add(Acc.id);
        }
        map<Id,Account> Acct = new map<id,Account>(Acclist);
        for(Account AC:Acclist){
        if(Acct.get(AC.id).Contacts.size()>0){
            AC.adderror('ERROR');
        }
        }
    }
    public void finish(Database.BatchableContext BC){
        
    }


 
Best Answer chosen by nilesh walke
Suraj Tripathi 47Suraj Tripathi 47
Hi Nilesh,

You can take reference from this below code.
Batch Trigger:-
trigger BatchTrigger on Account (after insert) {
    Map<id,Account> IdAccountMap=new Map<Id,Account>();
    for(Account acc:trigger.new){
        IdAccountMap.put(acc.id,acc);
    }
    if(IdAccountMap.size() > 0){
        database.executeBatch(new Demo3(IdAccountMap)); // Calling batch class.
    }
}
Batch Apex
global class Demo3 implements Database.Batchable<SObject> {
    
    Map<id,account> IdAccountMapBatch=new Map<id,account>();
    global Demo3(Map<id,account> IdAccountMap){
        IdAccountMapBatch=IdAccountMap;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([SELECT id,Name from account where id in:IdAccountMapBatch.keySet()]);
    }
    global void execute(Database.BatchableContext BC,List<Account> Acclist){
        list<contact> conList= new List<contact>();
        for(Account Acc:Acclist){
            contact con= new contact();
            con.lastName=acc.name;
            con.AccountId=acc.id;
            conList.add(con);
        }
        if(conList.size()>0){
            insert conList;
        }
    }
    global void finish(Database.BatchableContext BC){
        
    }
}
In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

Thanks and Regards
Suraj Tripathi.