You need to sign in to do that
Don't have an account?
sandy hello
Using batch job i have to create child records for the parent object with the help of existing other child object records. How can I achieve this using apex code.
I have to run a batch job to create child records for the parent object with the help of other child object records field information. Say i hav three objects A,B,C. Where A is the parent object and B,C are child objects, where B is already created, now i have to run batch job on parent A and taking the help of field information from child B i have to create other child C object records. Here C holds some other data other than B.How can i achieve this.
Here the code for above requirement where I have replicated on the Standard Objects Account, Opportunity and Contact as A,B and C as in above use case
please change the code as per ur requirement
*************************************************************************
public class BatchApexExp1 implements Database.Batchable<sObject>
{
public Database.QueryLocator start(Database.BatchableContext bc){
return Database.getQueryLocator([SELECT Id,Name,OwnerId,(SELECT id,AccountId,OwnerId FROM Opportunities)ops,(SELECT id,AccountId FROM Contacts)cns FROM Account WHERE Name = 'BatchAPEX_Acc1']);
}
public void Execute(Database.BatchableContext bc, List<Account> lstacc)
{
Boolean createCon = False;
Contact con = new Contact(); // To Create records on Object C
For(Account ac : lstacc)
{
createcon =False;
Opportunity op1 =ac.Opportunities;
if((ac.Opportunities.size()>0) && (ac.Contacts.size()==0))
{
If(ac.OwnerId == op1.OwnerId) // Checking/Using the field from Object B to create Record for Object C
{
con.LastName = 'xxx_'+ac.Name; // Give the name as per the requirement
con.AccountId = ac.Id;
createCon = True;
}
}
}
if (createCon == True)
{
Insert con;
}
}
public void Finish(Database.BatchableContext bc)
{
// Here Just to implement all the methods of Database.Batchable Interface.
// If needed write as per requirement.
}
}
************************************************************************************************
If you find Helpful.
Please mark it as Best Answer.
Thank you,
Prasanthi