{"id":3166,"date":"2023-11-21T11:33:36","date_gmt":"2023-11-21T11:33:36","guid":{"rendered":"https:\/\/www.emizentech.com\/blog\/?p=3166"},"modified":"2023-11-21T11:33:41","modified_gmt":"2023-11-21T11:33:41","slug":"database-stateful-in-batch-apex","status":"publish","type":"post","link":"https:\/\/multisitelocal.ezxdemo.com\/blog\/database-stateful-in-batch-apex.html","title":{"rendered":"How To Use Database. Stateful In Batch Apex In Salesforce"},"content":{"rendered":"\n<p>Firstly, we must understand that if we want to use Batch Apex, we must write an Apex Class that implements the Salesforce-provided interface Database. Batchable and then invoke the class programmatically. To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box, then select Apex Jobs. <\/p>\n\n\n\n<p>In this article, we delve into the powerful features of Database. Stateful in Batch Apex. Understanding Database. Stateful is essential for maintaining state across batch job executions, allowing developers to preserve instance variables and make more sophisticated, state-aware batch processes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Syntax for Batch:<\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\">global class BatchName implements Database.Batchable{}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Methods of Batch Class:<\/h3>\n\n\n\n<pre class=\"wp-block-preformatted\">global (Database.QueryLocator | Iterable) start (Database.BatchableContext bc) {\n\t\/\/Here we will add the query and return the result to execute method\n}\n\nglobal void execute (Database.BatchableContext BC, list&lt;P&gt;){\n\t\/\/Logic must be here\n}\n\nglobal void finish (Database.BatchableContext BC){\n\t\/\/after processing of all batches this method will be called. We can write any code inside it. Like if want to send email to all the records which are created or updated in the execute method.\n}<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Also Read: <a href=\"https:\/\/multisitelocal.ezxdemo.com\/blog\/create-custom-report-types-salesforce.html\">How To Create A Custom Report Type In Salesforce?<\/a><\/h4>\n\n\n\n<h3 class=\"wp-block-heading\">Implementing the Database.Batchable Interface<\/h3>\n\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">global class BatchAccountUpdate implements Database.Batchable{\n    String query = 'Select Name from Account WHERE Name! = null AND (Name = \\'Virendra Company\\' OR Name = \\'Virendra Sharma\\') ';\n    global Database.QueryLocator start (Database.BatchableContext bc) {\n        \/\/ collect the batches of records or objects to be passed to execute\n        return Database.getQueryLocator(query);\n    }\n    \n    global void execute (Database.BatchableContext bc, List records) {\n        \/\/ process each batch of records\n        for (Account acc : records){\n            acc.Name = acc.Name + '  Updated';\n        }\n        update records;\n    }\n    \n    global void finish (Database.BatchableContext bc){\n        \/\/ execute any post-processing operations, Calling batch class.\n        BatchUpdateAccountRelatedContacts b = new BatchUpdateAccountRelatedContacts();\n        Database.executeBatch(b, 200);\n    }    \n}\n<\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"\/blog\/wp-content\/uploads\/sites\/2\/2020\/06\/database-stateful-2.png\" alt=\"database stateful\" class=\"wp-image-3172\"\/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Database.Stateful<\/h2>\n\n\n\n<p>The following sample class finds all account records that are passed in by the start() method using a QueryLocator and updates the associated contacts with their account\u2019s mailing address. Finally, it sends off an email with the results of the bulk job and, since we are using Database.Stateful to track state, the number of records updated.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"\/blog\/wp-content\/uploads\/sites\/2\/2020\/06\/database-stateful-code-3.jpg\" alt=\"database stateful code\" class=\"wp-image-3173\"\/><\/figure><\/div>\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"\/blog\/wp-content\/uploads\/sites\/2\/2020\/06\/database-stateful-code-4.jpg\" alt=\"database stateful code\" class=\"wp-image-3174\"\/><\/figure><\/div>\n\n\n<p><strong>Example:<\/strong><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/multisitelocal.ezxdemo.com\/contact-us.html?utm_source=blog&amp;utm_medium=banner&amp;utm_campaign=emizen_blog\"><img decoding=\"async\" src=\"\/blog\/wp-content\/uploads\/sites\/2\/2020\/05\/hire-salesforce-developers-1.png\" alt=\"hire salesforce developers\" class=\"wp-image-2389\"\/><\/a><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\">Database.AllowsCallout<\/h3>\n\n\n\n<p>Database.AllowsCallout in Batch helps in integrating <a href=\"https:\/\/multisitelocal.ezxdemo.com\/salesforce.html\">Salesforce<\/a> with an external server. To use a callout in batch Apex, we must use an interface Database.AllowsCallouts in the class definition of batch class.<\/p>\n\n\n\n<p><strong>Syntax:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">global class SearchAndReplace implements Database.Batchable, Database.AllowsCallouts{}<\/pre>\n\n\n\n<p><strong>Example:<\/strong><br>\nHere, I am integrating the Opportunity object with Razorsync.com<br>\n\/*<br>\nGet service request from razorsync and update it into the salesforce<br>\n*\/<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">global class Batch_SR_RazorSyncAPI implements Database.Batchable, Database.AllowsCallouts{\n    global Database.QueryLocator start (Database.BatchableContext BC){\n        String query = 'SELECT Id, Razorsync_Service_Request_Id__c FROM Opportunity WHERE Razorsync_Service_Request_Id__c != null AND Razorsync_Job_Status__c != \\'Job Done\\' AND RazorSync_Status__c = \\'Success\\'';\n        return Database.getQueryLocator(query);\n    }\n   \n    global void execute (Database.BatchableContext BC, List scope){\n        String StatusId = '';\n        for (Opportunity s : scope){\n            \/\/get ServiceRequest\n            System.debug(s.Id);\n            Http http1 = new Http();\n            HttpRequest request1 = new HttpRequest();\n            request1.setEndpoint('https:\/\/DomainName.0.razorsync.com\/ApiService.svc\/ServiceRequest\/'+ s.Razorsync_Service_Request_Id__c);\n            request1.setMethod('GET');\n            request1.setHeader('Content-Type', 'application\/json');\n            request1.setHeader('Host', 'DomainName.0.razorsync.com');\n            request1.setHeader('Content-Length', '0');\n            request1.setHeader('Connection', 'Keep-Alive');\n            request1.setHeader('ServerName', 'DomainServerName');\n            request1.setHeader('Token', 'XXXXXXXXXXXXXXXXXXXXXXX');\n            \n            HttpResponse response1 = http1.send(request1);\n            \n            if(response1.getStatusCode() == 200) {\n                StatusId = '';\n                JSONParser parser = JSON.createParser(response1.getBody());\n                while(parser.nextToken() != null) {\n                    if( (parser.getCurrentToken() == JSONToken.FIELD_NAME) &amp;&amp; (parser.getText() == 'StatusId') || Test.isRunningTest()) {\n                        parser.nextToken();\n                        StatusId = parser.getText();\n                    }\n                }\n                System.debug(StatusId);\n                if(StatusId == String.valueOf(1) || Test.isRunningTest()){\n                    s.Razorsync_Job_Status__c = 'Job Done';\n                    s.StageName = 'Closed Won';\n                }else{\n                    s.Razorsync_Job_Status__c = 'Working';\n                }\n            }\n        }\n        update scope;\n    }\n    global void finish (Database.BatchableContext BC){\n    }\n}\n<\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Also Read: <a href=\"https:\/\/multisitelocal.ezxdemo.com\/blog\/salesforce-commerce-cloud-benefits.html\">Benefits of Salesforce Commerce Cloud<\/a> and <a href=\"https:\/\/multisitelocal.ezxdemo.com\/blog\/call-flow-from-apex.html\">How To Call Flows From Apex In Salesforce<\/a><\/h4>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>Using <strong>Database.Stateful<\/strong> in Batch Apex within Salesforce allows for preserving state across different execution methods in a batch job. This is crucial for scenarios where complex data processing is required, and the state must be retained between batch chunks.<\/p>\n\n\n\n<p>By implementing <strong>Database.Stateful<\/strong>, developers can ensure data consistency and manage large data sets effectively. However, it&#8217;s important to use this feature judiciously to avoid excessive memory consumption and potential performance issues.<\/p>\n\n\n\n<p>Best practices include keeping state variables minimal and focusing on essential data, thus making <strong>Database.Stateful<\/strong> a powerful tool for complex, state-dependent batch processing in Salesforce.<\/p>\n\n\n\n<p>For further assistance with a salesforce project, hire us as your salesforce consultant and reap the benefits.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Firstly, we must understand that if we want to use Batch Apex, we must write an Apex Class that implements the Salesforce-provided interface Database. Batchable and then invoke the class programmatically. To monitor or stop the execution of the batch Apex job, from Setup, enter Apex Jobs in the Quick Find box, then select Apex<\/p>\n","protected":false},"author":39,"featured_media":40477,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"MSN_Categories":"Uncategorized","MSN_Publish_Option":false,"MSN_Is_Local_News":false,"MSN_Is_AIAC_Included":"Empty","MSN_Location":"[]","MSN_Add_Feature_Img_On_Top_Of_Post":false,"MSN_Has_Custom_Author":false,"MSN_Custom_Author":"","MSN_Has_Custom_Canonical_Url":false,"MSN_Custom_Canonical_Url":"","_lmt_disableupdate":"no","_lmt_disable":"no","footnotes":""},"categories":[87],"tags":[],"class_list":{"0":"post-3166","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-salesforce-development"},"modified_by":"Marketing EmizenTech","featured_image_src":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-content\/uploads\/sites\/2\/2020\/06\/How-To-Use-Database.-Stateful-In-Batch-Apex-In-Salesforce-600x400.jpg","featured_image_src_square":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-content\/uploads\/sites\/2\/2020\/06\/How-To-Use-Database.-Stateful-In-Batch-Apex-In-Salesforce-600x408.jpg","author_info":{"display_name":"Virendra Sharma","author_link":"https:\/\/multisitelocal.ezxdemo.com\/blog\/author\/salesforce"},"_links":{"self":[{"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/posts\/3166","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/comments?post=3166"}],"version-history":[{"count":0,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/posts\/3166\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/media\/40477"}],"wp:attachment":[{"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/media?parent=3166"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/categories?post=3166"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/multisitelocal.ezxdemo.com\/blog\/wp-json\/wp\/v2\/tags?post=3166"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}