• WHO WE ARE
  • WHAT WE DO
    • Salesforce
      • Implementations
        • Sales Cloud
        • Service Cloud
        • CPQ
        • Field Service Lightning
        • Field Service for SMEs
      • Developments
        • Salesforce Customization
        • Custom Application Development
        • AppExchange Product Development
      • Migrations
        • Classic to Lightning Migration
        • Other Systems to Salesforce Migration
      • Integrations
    • Data Science
      • BI Solutions
      • AI/ML solutions
      • Agentic AI
  • HOW WE DO
    • Delivery Model
    • Our Works
  • REACH US
    • Contact Us
    • Careers
  • BLOG
    • WHO WE ARE
    • WHAT WE DO
      • Salesforce
        • Implementations
          • Sales Cloud
          • Service Cloud
          • CPQ
          • Field Service Lightning
          • Field Service for SMEs
        • Developments
          • Salesforce Customization
          • Custom Application Development
          • AppExchange Product Development
        • Migrations
          • Classic to Lightning Migration
          • Other Systems to Salesforce Migration
        • Integrations
      • Data Science
        • BI Solutions
        • AI/ML solutions
        • Agentic AI
    • HOW WE DO
      • Delivery Model
      • Our Works
    • REACH US
      • Contact Us
      • Careers
    • BLOG
  • [email protected]
  • (+91) 44-49521562
Merfantz - Salesforce Solutions for SMEs
Merfantz - Salesforce Solutions for SMEs
  • WHO WE ARE
  • WHAT WE DO
    • Salesforce
      • Implementations
        • Sales Cloud
        • Service Cloud
        • CPQ
        • Field Service Lightning
        • Field Service for SMEs
      • Developments
        • Salesforce Customization
        • Custom Application Development
        • AppExchange Product Development
      • Migrations
        • Classic to Lightning Migration
        • Other Systems to Salesforce Migration
      • Integrations
    • Data Science
      • BI Solutions
      • AI/ML solutions
      • Agentic AI
  • HOW WE DO
    • Delivery Model
    • Our Works
  • REACH US
    • Contact Us
    • Careers
  • BLOG

How to Clone Record Automatically Using Batch Apex

  • September 22, 2023
  • Tech Blogger
  • Uncategorized
  • 0

Description:

For more record DML operations and we can implement the batch class. Here is the example of how to clone the previous year record for the parent record with child and grandchild using batch class.

Example Apex Code:

Clone Records Using Batch Apex Class

global class CloneRecordsBatch implements Database.Batchable<sObject> {

 

global list<Parent_Object_Name__c> start(Database.BatchableContext context) {

String ParentRecordName = label.Clone;// which name you want

integer RecordYear = Date.Today().Year()-1;

List<Parent_Object_Name__c> clonesToInsert = Database.query(‘SELECT ‘ + String.join(new List<String>(Schema.getGlobalDescribe().get(‘Parent_Object_Name__c’).getDescribe().fields.getMap().keySet()), ‘,’) + ‘ FROM Parent_Object_Name__c where Parent_Object_Name__c =: ParentRecordName and CALENDAR_YEAR(CreatedDate) =: RecordYear’);

return clonesToInsert;

}

 

global void execute(Database.BatchableContext context, List<Parent_Object_Name__c> records) {

try

{

List<Parent_Object_Name__c> clonesToInsert = new List<Parent_Object_Name__c>();

List<string> SampleSetName = new List<string>();

list<id> SampleSetid = new list<id>();

list<string> SampleName = new list<string>();

for (Parent_Object_Name__c record : records) {

SampleSetName.add(record.id);

Parent_Object_Name__c SamSet = record.clone(false, false, false, false);

clonesToInsert.add(SamSet);

}

 

if (clonesToInsert.size() > 0) {

insert clonesToInsert;

}

for(Parent_Object_Name__c record: clonesToInsert)

{

SampleSetid.add(record.Id);

}

Map<id,list<Child_Object_Name__c>> sampleWithSampleSetMap = new Map<id,list<Child_Object_Name__c>>();

list<Child_Object_Name__c> SampleListToInsert = new list<Child_Object_Name__c>();

list<Child_Object_Name__c> SampleList = Database.query(‘SELECT ‘ + String.join(new List<String>(Schema.getGlobalDescribe().get(‘Child_Object_Name__c’).getDescribe().fields.getMap().keySet()), ‘,’) + ‘ FROM Child_Object_Name__c where Sample_Set__r.id IN: SampleSetName’);

if(SampleList.size() > 0)

{

for(Child_Object_Name__c Smp : SampleList)

{

if(!sampleWithSampleSetMap.containsKey(Smp.Parent_Object_Name__c))

{

sampleWithSampleSetMap.put(Smp.Parent_Object_Name__c,new list<Child_Object_Name__c>{Smp}); // Get Sample With Old Sample Set Id

}

else

sampleWithSampleSetMap.get(Smp.Parent_Object_Name__c).add(Smp);

}

}

 

for(id Ssetid : sampleWithSampleSetMap.keyset())

{

for(Child_Object_Name__c record : sampleWithSampleSetMap.get(Ssetid))

{

SampleName.add(record.Id);

if(SampleSetid.size() > 0)

{

record.Parent_Object_Name__c = SampleSetid[0];

}

Child_Object_Name__c Sam = record.clone(false, false, false, false);

SampleListToInsert.add(Sam);

}

if(SampleSetid.size() > 0)

SampleSetid.remove(0);

}

list<id> sampleid = new list<id>();

 

if(SampleListToInsert.size() > 0)

{

insert SampleListToInsert;

}

for(Child_Object_Name__c record : SampleListToInsert)

{

sampleid.add(record.Id);

}

Map<id,list<GrandChild_Object_Name__c>> TestMap = new Map<id,list<GrandChild_Object_Name__c>>();

 

list<GrandChild_Object_Name__c> TestToInsert = new list<GrandChild_Object_Name__c>();

list<GrandChild_Object_Name__c> TestList = Database.query(‘SELECT ‘ + String.join(new List<String>(Schema.getGlobalDescribe().get(‘GrandChild_Object_Name__c’).getDescribe().fields.getMap().keySet()), ‘,’) + ‘ FROM GrandChild_Object_Name__c where Child_Object_Name__c IN:SampleName’);

if(TestList.size() > 0)

{

for(GrandChild_Object_Name__c record : TestList)

{

if(!TestMap.containskey(record.Child_Object_Name__c))

{

TestMap.put(record.Child_Object_Name__c,new list<GrandChild_Object_Name__c>{record});

}

else

TestMap.get(record.Child_Object_Name__c).add(record);

}

}

 

for(id samid : TestMap.keyset())

{

for(GrandChild_Object_Name__c record : TestMap.get(samid))

{

if(sampleid.size() > 0)

{

record.Child_Object_Name__c = sampleid[0];

}

GrandChild_Object_Name__c Sam = record.clone(false, false, false, false);

TestToInsert.add(Sam);

}

if(sampleid.size() > 0)

sampleid.remove(0);

}

 

if(TestToInsert.size() > 0)

{

insert TestToInsert;

}

}

catch(Exception e)

{

system.debug(‘Exception raised due to —->’+e);

}

}

 

global void finish(Database.BatchableContext context) {

 

}

}

Here, the example Clone Records Using Batch Apex Schedule Class

For using the scheduled apex, you can schedule the below class for the every year starting.

public class CloneRecordBatchSchedule implements Schedulable{

public void execute (SchedulableContext sc)

{

CloneRecordsBatch  crb = new CloneRecordsBatch();

Database.executeBatch(crb);

}

}

Conclusion:

           By implementing this functionality, we can easily manage our data in Salesforce.

Related Link : https://merfantz.com/blog/part-iv-7-batch-class-creation-in-salesforce/

Write a test class for batch class in Salesforce

Author Bio

Tech Blogger
+ Recent Posts
  • May 2, 2025
    Salesforce API Integrations: Connect with Slack, Zoom, and Teams
  • Guide to Streamlining Sales Success
    April 17, 2025
    Mastering Salesforce CPQ: A Comprehensive Guide to Streamlining Sales Success
  • April 4, 2025
    Unlocking Salesforce Data Cloud: Unify and Activate Customer Data
  • Salesforce Agentforce The Ultimate AI Guide
    March 27, 2025
    Salesforce Agentforce: The Ultimate AI Guide
Tags: how to clone record using batch apexMerfantz Featuressalesforce batch apex class
  • Previous Are You Ready to Unlock the Power of Salesforce Community Cloud? | Merfantz
  • Next How to Freeze Column and Header using Visualforce Page
Merfantz Technologies is a leading Salesforce consulting firm dedicated to helping small and medium enterprises transform their operations and achieve their goals through the use of the Salesforce platform. Contact us today to learn more about our services and how we can help your business thrive.

Discover More

Terms and Conditions
Privacy Policy
Cancellation & Refund Policy

Contact Info

  • No 96, 2nd Floor, Greeta Tech Park, VSI Industrial Estate, Perungudi, Chennai 600 096, Tamil Nadu, INDIA
  • (+91) 44-49521562
  • [email protected]
  • 9:30 IST - 18:30 IST

Latest Posts

Salesforce API Integrations: Connect with Slack, Zoom, and Teams May 2, 2025
Guide to Streamlining Sales Success
Mastering Salesforce CPQ: A Comprehensive Guide to Streamlining Sales Success April 17, 2025
Unlocking Salesforce Data Cloud: Unify and Activate Customer Data April 4, 2025

Copyright @2023 Merfantz Technologies, All rights reserved