Passing Parameter to batch apex

I need to pass parameter to the batch apex class.
This is apex class:

global class batchNotesInsert implements Database.Batchable<sObject> {

  global Database.QueryLocator start(Database.BatchableContext BC) {

        String query = 'select id,Parent.name,Parent.Type,Title,body from note';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Note> scope) {

         List<ShowNotes__c> shn = new List<ShowNotes__c>();
         for(Note a : scope)
         {

             shn.add
             (
                 new ShowNotes__c
                 (
                     Name = a.Parent.name,
                     Title__c = a.Title,
                     Content__c = a.body,
                     ParentOfNotes__c = a.Parent.Type
                 )
             );                  
         }

         insert shn;   

    }   

    global void finish(Database.BatchableContext BC) {
    }
}

Controller Code:

public class callNotesbatchcls { 

  Public PageReference callingMethod() 
  { 
       batchNotesInsert shn = new batchNotesInsert(); 
       database.executeBatch(shn); return null; 
   } 
} 

Thank you.

Answer

Pass in constructor.

public class callNotesbatchcls { 

    Public PageReference callingMethod() 
    { 
        batchNotesInsert shn = new batchNotesInsert('Testing here'); 
        database.executeBatch(shn ); return null; 
    } 
} 

batch

global class batchNotesInsert implements Database.Batchable<sObject>, Database.Stateful {

    private String strParameter;

    public batchNotesInsert(String strParam) {
        strParameter = strParam;
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'select id,Parent.name,Parent.Type,Title,body from note';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<Note> scope) {
        system.debug('==========check string====='+strParameter);    
    }   

    global void finish(Database.BatchableContext BC) {
    }
}

Yes Like @Eric and @crop1645 said.

If you don’t specify Database.Stateful, all static and instance member
variables are set back to their original values.

If you do not use database.stateful then any changes made to the
parameter during the execute method are not persisted across batches
and the next execute method will be the original value. You can test
this by adding strParameter += ‘–Added String’ and you will see that
the debugged value for each execute method is the original value

If we are modifying strParameter in execute method then still it will have its original value. maintain the updated value in strParameter we need database.stateful

Note: If you are not modifying strParameter value in execute method then no need to use database.stateful

Attribution
Source : Link , Question Author : Jana Shree , Answer Author : Community

Leave a Comment