Thursday, February 19, 2015

Salesforce Integration with SOAP API - Part 7 - Create Account records with Java program

Preface - This post is part of "Salesforce Integration with SOAP API" series.

As of now we have understood how we can query one or more record from Salesforce using query() and queryMore() methods. The posts are @
But what about creating records –

Create() method is used to create one or more records in the Salesforce Org. This is basically doing the INSERT operation. The basic steps are given below –
  • Create an array of sObject[] where each sObject is basically the record you want to create. You need to populate all the required fields.
  • Call create(), passing the sObject[] array
  • Process the results in the SaveResult[] object.
We should understand the below important points before going into the coding –
  • API generates the unique ID fields automatically. As a developer, we can’t explicitly set the value of ID
  • There are few other fields also getting generated automatically and we can’t set them explicitly. The fields are CreatedDate, CreatedById, LastModifiedDate, LastModifiedById and SystemModstamp.
  • For all required fields, if there is no default values, as a developer you need to provide the values.
  • For all non-required fields, if you don’t provide any values, API will put null.
  • As a developer, you need to respect the referential integrity. For example – while creating the child record you need to supply the foreign key information that will link child with parent.
  • While creating Account, Case or Lead, developer can make sure newly created Cases or Leads can be assigned to one or more users as per the assignment rule configured. You need to check AssignmentRuleHeader option.
  • Your client application can create maximum 200 records in a single call of create(). If the create request exceeds 200 records, then the entire operation will fail.
  • The AllOrNoneHeader allows you to define the roll back behavior. The default behavior is to allow successful records to be committed while marking records with error as failed.
  • As a developer, you can create multiple different types of object in a single create() call. You can create upto 10 different object type records in a single call. Records of different object types are broken into chunks and committed chunk wise. If there is any trigger on that object, that trigger will be called once per chunk. Each call can process upto 10 chunks.
  • Records are always saved in the same order that they are entered in the sObject[] array. So if you are entering two object records having parent-child relationship, you need to make sure parent is added first followed by child in the sObject[] array.
  • You can’t add a record that references another record of same object type in the same call. It’s like self – reference. If an account is having parent account, then you can’t insert account and parent account in the same call.
Note: I have written a helper class ConnectionHelper.java which I am using to connect to Salesforce using Enterprise WSDL. To know more about that, please refer my previous post @ 
Now below code will create two Account records - 
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.soap.enterprise.Error;

public class CreateAccount {
    private EnterpriseConnection connection;
    
    private CreateAccount(){
        setConnection(ConnectionHelper.doConnect());
    }
    
    public static void main(String[] args) {
        CreateAccount createAccount = new CreateAccount();
        createAccount.doCreateAccount();
    }
    
    private void doCreateAccount(){
        
        Account account1 = new Account();
        account1.setName("Test Account 1");
        account1.setAccountNumber("11111");
        account1.setRating("Hot");
        account1.setPhone("888888");
        
        Account account2 = new Account();
        account2.setName("Test Account 2");
        account2.setAccountNumber("11111");
        account2.setRating("Hot");
        account2.setPhone("888888");
        
        try{
            SaveResult[] results = getConnection().create(new SObject[]{account1, account2});
            
            //Check the result
            for(SaveResult result : results){
                if(result.isSuccess()){
                    System.out.println("Account created with ID: " + result.getId());
                }else{
                    for(Error anError : result.getErrors()){
                        System.out.println("Error occurred: " + anError.getMessage());
                    }
                }
            }
        }catch(ConnectionException e){
            e.printStackTrace();
        }
    }

    public EnterpriseConnection getConnection() {
        return connection;
    }

    public void setConnection(EnterpriseConnection connection) {
        this.connection = connection;
    }

}


We can create parent - child object relationship also using java program. Before that please find what Salesforce documented -

Now let's check the code below -
import java.util.Calendar;

import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.Error;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;
import com.sforce.soap.enterprise.sobject.Opportunity;
import com.sforce.soap.enterprise.sobject.SObject;
import com.sforce.ws.ConnectionException;


public class CreateOpportunityWithAccount {

    private EnterpriseConnection connection;
    private CreateOpportunityWithAccount(){
        setConnection(ConnectionHelper.doConnect());
    }
    
    public static void main(String[] args) {
        CreateOpportunityWithAccount createOpportunityWithAccount = new CreateOpportunityWithAccount();
        createOpportunityWithAccount.doCreateOpportunityWithAccount();
    }
    
    private void doCreateOpportunityWithAccount(){
        try{
            Opportunity anOpportunity = new Opportunity();
            anOpportunity.setName("TEST OPPORTUNITY");
            anOpportunity.setStageName("Prospecting");
            Calendar date = getConnection().getServerTimestamp().getTimestamp();
            date.add(Calendar.DAY_OF_MONTH, 7);
            anOpportunity.setCloseDate(date);
            
            //Create the parent reference. This will be used only for foreign key reference and this should not contain any other field.
            Account refAccount = new Account();
            refAccount.setAccount_External_ID__c("TEST00001");
            anOpportunity.setAccount(refAccount);
            
            //Create the account object. This will be used to create the account
            Account parentAccount = new Account();
            parentAccount.setName("TEST PARENT ACCOUNT");
            parentAccount.setAccount_External_ID__c("TEST00001");
            
            //Create both Account and Opportunity
            //Here the order is very important. parentAccount should be created first followed by anOpportunity, 
            //otherwise the creation of opportunity will fail due to foreign key, but
            //Account will still be created
            SaveResult[] results = getConnection().create(new SObject[]{parentAccount, anOpportunity});
            
            
            //Check the results
            for(SaveResult aResult : results){
                if (aResult.isSuccess()){
                    System.out.println("Successfully created with ID: " + aResult.getId());
                }else{
                    for(Error anError : aResult.getErrors()){
                        System.out.println("Error message: " + anError.getMessage());
                    }
                }
            }
        }catch(ConnectionException e){
            e.printStackTrace();
        }
    }

    public EnterpriseConnection getConnection() {
        return connection;
    }

    public void setConnection(EnterpriseConnection connection) {
        this.connection = connection;
    }

}


Hope this will help you to understand the process. Appreciate your feedback.

Wishing you a nice weekend. Cheers

0 comments:

Post a Comment