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');
}
}
upsert
statement. The code would be like this:upsert newObjects ExternalId;