欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Use Batch Apex

发布时间:2025/4/16 编程问答 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Use Batch Apex 小编觉得挺不错的,现在分享给大家,帮大家做个参考.



如果您有很多记录要处理,例如数据清理或归档,则Batch Apex可能是您最好的解决方案。



假设您要使用Batch Apex处理100万条记录。

对于要处理的每批记录,一次调用批处理类的执行逻辑。

每次调用批处理类时,该作业都会被放置在Apex作业队列中,并作为离散事务执行

此功能有两个很棒的优点:







在批处理Apex中使用状态

Batch Apex通常是无状态的。批处理Apex作业的每次执行均被视为离散事务。

例如,一个包含1,000条记录并使用默认批处理大小的批处理Apex作业被视为5个事务,每个事务200条记录。



假设您有一项业务要求,其中规定,美国公司的所有联系人都必须以其母公司的Account 地址作为其邮寄地址。

不幸的是,用户正在输入没有正确地址的新联系人!

编写一个Batch Apex类,以确保强制执行此要求。

global class UpdateContactAddresses implements Database.Batchable<sObject>, Database.Stateful {// instance member to retain state across transactionsglobal Integer recordsProcessed = 0;global Database.QueryLocator start(Database.BatchableContext bc) {return Database.getQueryLocator('SELECT ID, BillingStreet, BillingCity, BillingState, ' +'BillingPostalCode, (SELECT ID, MailingStreet, MailingCity, ' +'MailingState, MailingPostalCode FROM Contacts) FROM Account ' + 'Where BillingCountry = \'USA\'');}global void execute(Database.BatchableContext bc, List<Account> scope){// process each batch of recordsList<Contact> contacts = new List<Contact>();for (Account account : scope) {for (Contact contact : account.contacts) {contact.MailingStreet = account.BillingStreet;contact.MailingCity = account.BillingCity;contact.MailingState = account.BillingState;contact.MailingPostalCode = account.BillingPostalCode;// add contact to list to be updatedcontacts.add(contact);// increment the instance member counterrecordsProcessed = recordsProcessed + 1;}}update contacts;} global void finish(Database.BatchableContext bc){System.debug(recordsProcessed + ' records processed. Shazam!');AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.EmailFROM AsyncApexJobWHERE Id = :bc.getJobId()];// call some utility to send emailEmailUtils.sendMessage(job, recordsProcessed);} }

测试批处理Apex

由于Apex开发和测试是并行进行的

@isTest private class UpdateContactAddressesTest {@testSetup static void setup() {List<Account> accounts = new List<Account>();List<Contact> contacts = new List<Contact>();// insert 10 accountsfor (Integer i=0;i<10;i++) {accounts.add(new Account(name='Account '+i, billingcity='New York', billingcountry='USA'));}insert accounts;// find the account just inserted. add contact for eachfor (Account account : [select id from account]) {contacts.add(new Contact(firstname='first', lastname='last', accountId=account.id));}insert contacts;}static testmethod void test() { Test.startTest();UpdateContactAddresses uca = new UpdateContactAddresses();Id batchId = Database.executeBatch(uca);Test.stopTest();// after the testing stops, assert records were updated properlySystem.assertEquals(10, [select count() from contact where MailingCity = 'New York']);}}



Create an Apex class that uses Batch Apex to update Lead records

LeadProcessor.apxc

global class LeadProcessor implements Database.Batchable<Sobject> {global Database.QueryLocator start(Database.BatchableContext bc) {return Database.getQueryLocator([Select LeadSource From Lead ]);}global void execute(Database.BatchableContext bc, List<Lead> scope){for (Lead Leads : scope) {Leads.LeadSource = 'Dreamforce';}update scope;} global void finish(Database.BatchableContext bc){ } }

LeadProcessorTest.apxc

@isTest public class LeadProcessorTest {static testMethod void testMethod1(){List<Lead> lstLead = new List<Lead>();for(Integer i=0 ;i <200;i++){Lead led = new Lead();led.FirstName = 'FirstName';led.LastName = 'LastName' +i;led.Company = 'demo' +i;lstLead.add(led);}insert lstLead;Test.startTest();LeadProcessor obj = new LeadProcessor();Database.executeBatch(obj);Test.stopTest();} }

 

总结

以上是生活随笔为你收集整理的Use Batch Apex的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。