Skip to content

Updating Records via Batch Apex Part 1

I’ve put together a batch class that’s great for quick records updates, without using the dataloader!  This comes in handy when a new trigger or workflow is setup and an action needs applied to a large amount of records.  Generally, to accomplish this a user would have to export the records with Ids in question either through a report or the dataloader then send them through the dataloader in an update.  With this class however, an administrator can plug in a simple query like ‘SELECT Id FROM Contact’ and run the below from the Developer Console, or another third party tool like the SqolXplorer by executing the following command:


string query = 'SELECT Id FROM Contact';

ID idBatch = Database.executeBatch(new util_sObjectUpdaterBatch(query), 200);

Here’s the class code, which can also be found on my GitHub here:

global class util_sObjectUpdaterBatch implements Database.Batchable<sobject>{

    /**
    Run This Batch

    string query = '';

    ID idBatch = Database.executeBatch(new util_sObjectUpdaterBatch(query), 200);
    **/

    global string query;

    global util_sObjectUpdaterBatch(string q) {

        query = q;

    }

    global Database.QueryLocator start(Database.BatchableContext bcMain) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext bcMain, List<sObject> scope) {

        if(scope.size() > 0) {
            update scope;
        }

    }

    global void finish(Database.BatchableContext bcMain) {

    } 

}

Here’s the test class:

@isTest
private class testutil_sObjectUpdaterBatch{

    static account acct;
    static list<contact> contacts;

    private static void init(){

        acct = new account(
            name = 'Test Account'
        );

        insert acct;

        contacts = new list<contact>();

        for(integer i = 0; i < 200; i++){
            contacts.add(new contact(
                firstName = 'Sample',
                lastName = 'Contact - '+i,
                accountId = acct.id
            ));
        }

        insert contacts;

    }

    @isTest static void test_util_sObjectUpdaterBatch() { 

        init();

        test.startTest();

            string query = 'SELECT Id FROM Contact';

            id thisBatchId = Database.executeBatch(new util_sObjectUpdaterBatch(query), 200);

        test.stopTest();

        //make sure there are 200 contacts
        system.assertEquals(200,contacts.size());

        asyncApexJob thisJob = [SELECT id, status, jobItemsProcessed, numberOfErrors, totalJobItems FROM asyncApexJob WHERE id =: thisBatchId];

        //make sure job was completed
        system.assertEquals('Completed',thisJob.status);
        //make sure 1 job was processed
        system.assertEquals(1,thisJob.jobItemsProcessed);
        //make sure there were 0 errors
        system.assertEquals(0,thisJob.numberOfErrors);

    }

}

 

In my next post I’ll show you how to run updates and change field values through a batch class!  Which is now up here, Updating Records via Batch Apex Part 2: Field Changes.

Published inApexBatch Apex

Be First to Comment

Leave a Reply