I am trying to insert new contacts and leads in salesforce using external api call in apex batch. I am running once in a day and inserting 500 contacts or leads in salesfoce. But my batch file is inserting duplicate contacts with same email address. I want to skip contact or lead records to insert when same email id already exists with another record.
If I check email address using query for each record then the SOQL query limit will be a problem.
How I can avoid duplicate insert in contacts or lead in salesforce.
Thanks in Advance Rajendra J.
Apex code:
request.setMethod('GET'); request.setTimeout(120000); request.setEndpoint('http://api.nurturehq.com/contacts/many?nurture_id='+last_insert_id+'&limit=10&auth_token='+obj_authentication.nurture_authentication_key__c); request.setHeader('X-Api-Version', '2.0'); request.setHeader('X-Access-Id', 'APP_ID3MVG9A2kN3Bn17hvx6UytrOeZp67_J835ecdoZ5eJmyC_BQS227UFPVb5KgNJW7YpVd9oTA6sCJ19msqZQ9sY'); request.setHeader('X-Access-Secret', 'SECRET_KEY4317178691269588217'); JSONParser parser = JSON.createParser(response.getBody()); // system.debug('jsondataaaa'+parser); NurtureSingleton__c nurSingle = [SELECT nurture_last_insert_contact_id__c FROM NurtureSingleton__c limit 1]; List listContacts = new List(); while (parser.nextToken() != null) {
if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
while (parser.nextToken() != null) {
if (parser.getCurrentToken() == JSONToken.START_OBJECT){
Contacts cnts = (Contacts)parser.readValueAs(Contacts.class);
first_name=cnts.first_name;
last_name=cnts.last_name;
if(String.isEmpty(first_name)) {
first_name='-';
}
if(String.isEmpty(last_name)) {
last_name='-';
}
listContacts.add(new Contact(FirstName = first_name , LastName = last_name,Email=cnts.email,Title=cnts.title,Birthdate=cnts.birthdate,Phone=cnts.phone,
MobilePhone=cnts.mobile,Fax=cnts.fax,Description=cnts.description,LeadSource=cnts.lead_source,MailingCity=cnts.city,MailingState=cnts.state,
MailingPostalCode = cnts.zip, MailingCountry = cnts.country,Department=cnts.department,Salutation=cnts.Salutation,
MailingStreet=cnts.address,Nurture_contact_id__c=cnts.id,AccountId=cnts.salesforce_account_id));
nurSingle.nurture_last_insert_contact_id__c = cnts.id;
//insert listContacts;
}
}
}
}
insert listContacts;