0

I need to extract records from an external application database table and Create a new table (custom object named CustomObj) in Salesforce to receive the data upload (upsert this based on the id using Data Loader).

I need to create an Apex Batch job so that it can be scheduled and from the uploaded data, need to create SOQL statement to fetch some fields from CustomObj and Upsert those fields to Product2 object in Salesforce.

My issue is when I run the Apex Batch job second time it inserts the same set of records again in Product2 object when it should have done the update operation. It causes duplicate records in Product2 object. Below is my code to have a look. Please help me.

     global class ProductUpsertBatch implements Database.Batchable<sobject> 
     {
      // Start Method
      global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('Select id, ExternalAppUniqueId__c, Name, Description__c, Category__c, uom__c, Cost_Price__c From CustomObj__c');
   }
   //execute method
   global void execute(Database.BatchableContext bc, List<sObject> scope) {

       list<Product2> newObjects = new list<Product2>();

       for(Sobject s : scope){
           CustomObj__c obj = (CustomObj__c) s;
           newObjects.add(new Product2(
               ExternalId = obj.id,
               ProductCode = obj.Name,
               Name = obj.Formula_Description__c,
               QuantityUnitOfMeasure = obj.uom__c,
               Description = obj.Category__c,
               Cost_Price__c = obj.cost_price__c
           ));
       }
       upsert newObjects;
           }
   //finish method
   global void finish(Database.BatchableContext bc) {
      system.debug('ProductUpsertBatch is finished processing');
   }

}

1
  • You need to provide the external id in upsert statement. The code would be like this: upsert newObjects ExternalId; Feb 24, 2018 at 8:43

1 Answer 1

1

Make sure you use this:

upsert newObjects ExternalId

Also, the running user must have "View All" permission on Product2 object to avoid any duplicate creation.

1
  • They only need View All if the field is not unique.
    – Adrian Larson
    Feb 24, 2018 at 14:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .