I want to process only the new records in a batch Apex. We can query the new records in a trigger by Trigger.new . Is there any means by which we can query only the newly created data items and process them in a batch class program? I want to update the records upon their creation. Thanks in advance.
I want my batch to be running every night, and i need to query all the orders created that date. Next i want to see the opportunites that have those orders, and upsert only them. This i want to do so that the batch query only the newly created data items, since it is currently querying all the data and is taking very long time to finish execution. Here is my code:
Giving its brief description: I am upserting a lookup field Order_History__c which is a link to OrderHistory (API name - Order_History__c) object. ID_Opp_Product_18__c, Sales_Order__c (referencing field in OpportunityLineItem), and Order_History__c are present as Custom Fields and Relationship in OpportunityLineItem.
global class OrderHistoryBatch implements Database.Batchable<sObject>
{
String query;
//String email;
global Database.QueryLocator start(Database.BatchableContext BC)
{
query = 'select iD, Name from Sales_Order__c'; //need to define query
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope)
{
List<Sales_Order__c> soorders = (List<Sales_Order__c>)scope;
Map<String, ID> salesOrderMap = new Map<String, ID>();
for (Sales_Order__c so : soorders) {
String s2 = String.valueOf(so.Name);
String s1 = s2.mid(2,8);
if (s1 != null) {
salesOrderMap.put(s1, so.Id);
}
}
List <OpportunityLineItem> oppLineItems = [select Sales_Order__c, OpportunityId,ID_Opp_Product_18__c from OpportunityLineItem where Sales_Order__c In :salesOrderMap.keyset()];
for(OpportunityLineItem oli : oppLineItems) {
ID salesOrderId = salesOrderMap.get(oli.Sales_Order__c);
oli.Order_History__c = salesOrderId;
}
upsert oppLineItems;
}
global void finish(Database.BatchableContext BC)
{
}
}
Please can anyone help me out in this. I need to wrap it up and deploy in next couple of hours. Thanks in advance.