+ Start a Discussion
SurpriseSurprise 

Upsert and java

Hi Friends,


I have taken Below given sample from teh salesforce help as it is .All I need to understand upsert fuinctionality so that I can use it in my own project.

 

Below example is creating two accounts and setting some values in the Externalid field along with the other values and then storing those records in the the array in the 1 and 2 index position of the array and then using connection.upsert and providing externalid and array as arguments For example,

 

Connection.upsert("MyExtId__c", upserts);

 

My Question ,From where is connection.upsert () function geting externalid value.Can somebody please help.

 

 

 

This sample upserts two accounts using a custom external ID field called MyExtId__c. The upsert() call matches the accounts based on the MyExtId__c field in order to determine whether to create or update the accounts. Before running this sample, change the MyExtId__c field name to an existing custom ID field name in your org.

 

public void upsertRecords() {

   SObject[] upserts = new Account[2];

 

   Account upsertAccount1 = new Account();

   upsertAccount1.setName("Begonia");

   upsertAccount1.setIndustry("Education");

   upsertAccount1.setMyExtId__c("1111111111");

   upserts[0] = upsertAccount1;

 

   Account upsertAccount2 = new Account();

   upsertAccount2 = new Account();

   upsertAccount2.setName("Bluebell");

   upsertAccount2.setIndustry("Technology");

   upsertAccount2.setMyExtId__c("2222222222");

   upserts[1] = upsertAccount2;

 

   try {

      // Invoke the upsert call and save the results.

      // Use External_Id custom field for matching records.

      UpsertResult[] upsertResults = connection.upsert(

                                  "MyExtId__c", upserts);

      for (UpsertResult result : upsertResults) {

         if (result.isSuccess()) {

            System.out.println("\nUpsert succeeded.");

            System.out.println((result.isCreated() ? "Insert" : "Update")

                  + " was performed.");

            System.out.println("Account ID: " + result.getId());

         } else {

            System.out.println("The Upsert failed because: "

                  + result.getErrors()[0].getMessage());

         }

      }

   } catch (ConnectionException ce) {

      ce.printStackTrace();

   }

 

Vinita_SFDCVinita_SFDC

Hello,

The external id value is defined in following lines of code for Account1 and Account2 respectively:

upsertAccount1.setMyExtId__c("1111111111");

upsertAccount2.setMyExtId__c("2222222222");

 

Also please refer following links for better understanding of Upsert functionality:

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_dml_examples_upsert.htm

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_upsert.htm

 

SurpriseSurprise

Thanks Vinita,

 

I understand that we are explicitly providing the external id values to the account record in salesforce and we have not yet persisted salesforce record to the database.,Therefore, as of now,account record only exists in memory.

 

Now,please look at the code below.Below given line is actually doing the upsert functionality and MyExtId__c is the custom field on the account object .Now when the below given line executes then salesforce try to fetch the MyExtId__c  value from the salesforce database and look for the same id in the Upserts array.If it finds one then the account record values are used to update the record in the  salesforce database.If it does not find external id in the salesforce database then it inserts the new record and also external id value with the record .I am trying to undertsand before I start using it.Can u please verify if I am thinking correctly .

 

UpsertResult[] upsertResults = connection.upsert( "MyExtId__c", upserts)

 

 

Thanks a lot for your help,

Surprise.

Vinita_SFDCVinita_SFDC

Hello,

 

You are right, “upsert” is a combination of inserting and updating - if a record in your file (or in your code) matches an existing record, the existing record is updated with the values in your file. If no match is found, then the record is created as new.

 

I would suggest to try implementing any DML operation (insert,upsert,delete) with data loader in a test Org before implementing it through code. It will give you a better understanding.

SurpriseSurprise

Thanks Vinita,

 

I am trying to connect salesforce to salesforce using enterprise wsdl.I have succesfully used wsdl login() api which returns sessionid and URL .So another request needs to have these two setup .I am stuck ,if u know can u please help me.

 

I am not using rest api's in any way.Everthing here is purely sopa based.I am trying to connect salesforce to salesforcce so that changes in one org can be reflected in another salesoforce org.So I am consuming enterprise wsdl of the salesforce other org and generating wsdl to apex classes and using it's login functionlaity to establish connection with the other org and finally I am tryiing to query some records using query Api of the enterprise Wsdl.


When I run below given code it gives me an error by saying that destinaltion URL is not reset.I understand that First call to the login() api uses different URL and then login() api returns another url which we need to send with the subsequent  API' calls and session ID as well.Can u help in setting up sesion id and Destination URL

 

 

In the end is the WSDl to apex generated classes is given.

Below given  code I am trying from Anonynous block.


enterpriseSoapSforceCom.LoginResult lr=new enterpriseSoapSforceCom.LoginResult();
enterpriseSoapSforceCom.soap s=new enterpriseSoapSforceCom.soap();

lr=s.login('xxxxxxxx@yahoo.com','yyyyyyyyy);
String g=lr.sessionid;
System.debug('The value of the session id in the new variable s is'+g);
string url=lr.serverurl; // This is the returned URL from login api.How to setup this so that  it goes with the object calling query() api.


system.debug('The value of the url in the new variable s is'+url);
s.inputHttpHeaders_x = new Map<String, String>();  //
//Setting a basic authentication header
s.inputHttpHeaders_x.put('Authorization', 'g');Setting up input headers and assigning  session id to the header as per salesforce documentation
//s.inputHttpHeaders_x .put('New Url',url);
QueryResult qResult = null;
System.debug('The value of the session id in the new variable s is'+s);
String soqlQuery='SELECT name FROM Contact';
qResult = s.query(soqlQuery);//Calling Query APi fo the enterprise Wsdl
System.debug('The value of the opportunity object opp is'+qResult);


 

 

public class enterpriseSoapSforceCom {
    public class getUserInfo_element {
        private String[] apex_schema_type_info = new String[]{'urn:enterprise.soap.sforce.com','true','

false'};
        private String[] field_order_type_info = new String[]{};
    }
    public class LoginResult {
        public String metadataServerUrl;
        public Boolean passwordExpired;
        public Boolean sandbox;
        public String serverUrl;
        public String sessionId;
        public String userId;
        public enterpriseSoapSforceCom.GetUserInfoResult userInfo;
        private String[] metadataServerUrl_type_info = new String[]{'metadataServerUrl','http://www.w3.org/2001/XMLSchema','string','1','1','true'};
        private String[] passwordExpired_type_info = new String[]{'passwordExpired','http://www.w3.org/2001/XMLSchema','boolean','1','1','false'};
        private String[] sandbox_type_info = new String[]{'sandbox','http://www.w3.org/2001/XMLSchema','boolean','1','1','false'};
        private String[] serverUrl_type_info = new String[]{'serverUrl','http://www.w3.org/2001/XMLSchema','string','1','1','true'};
        private String[] sessionId_type_info = new String[]{'sessionId','http://www.w3.org/2001/XMLSchema','string','1','1','true'};
        private String[] userId_type_info = new String[]{'userId','urn:enterprise.soap.sforce.com','ID','1','1','true'};
        private String[] userInfo_type_info = new String[]{'userInfo','urn:enterprise.soap.sforce.com','GetUserInfoResult','0','1','false'};
        private String[] apex_schema_type_info = new String[]{'urn:enterprise.soap.sforce.com','true','false'};
        private String[] field_order_type_info = new String[]{'metadataServerUrl','passwordExpired','sandbox','serverUrl','sessionId','userId','userInfo'};
    }
    
    public class Soap {
        public String endpoint_x = 'https://login.salesforce.com/services/Soap/c/28.0/0DFi0000000PCEo';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        public enterpriseSoapSforceCom.QueryOptions_element QueryOptions;
        public enterpriseSoapSforceCom.EmailHeader_element EmailHeader;
        public enterpriseSoapSforceCom.DebuggingInfo_element DebuggingInfo;
        public enterpriseSoapSforceCom.MruHeader_element MruHeader;
        public enterpriseSoapSforceCom.PackageVersionHeader_element PackageVersionHeader;
        public enterpriseSoapSforceCom.SessionHeader_element SessionHeader;
        public enterpriseSoapSforceCom.UserTerritoryDeleteHeader_element UserTerritoryDeleteHeader;
        public enterpriseSoapSforceCom.LoginScopeHeader_element LoginScopeHeader;
        public enterpriseSoapSforceCom.AllowFieldTruncationHeader_element AllowFieldTruncationHeader;
        public enterpriseSoapSforceCom.DebuggingHeader_element DebuggingHeader;
        public enterpriseSoapSforceCom.AllOrNoneHeader_element AllOrNoneHeader;
        public enterpriseSoapSforceCom.LocaleOptions_element LocaleOptions;
        public enterpriseSoapSforceCom.OwnerChangeOptions_element OwnerChangeOptions;
        public enterpriseSoapSforceCom.AssignmentRuleHeader_element AssignmentRuleHeader;
        public enterpriseSoapSforceCom.DisableFeedTrackingHeader_element DisableFeedTrackingHeader;
        public enterpriseSoapSforceCom.StreamingEnabledHeader_element StreamingEnabledHeader;
        private String QueryOptions_hns = 'QueryOptions=urn:enterprise.soap.sforce.com';
        private String EmailHeader_hns = 'EmailHeader=urn:enterprise.soap.sforce.com';
        private String DebuggingInfo_hns = 'DebuggingInfo=urn:enterprise.soap.sforce.com';
        private String MruHeader_hns = 'MruHeader=urn:enterprise.soap.sforce.com';
        private String PackageVersionHeader_hns = 'PackageVersionHeader=urn:enterprise.soap.sforce.com';
        private String SessionHeader_hns = 'SessionHeader=urn:enterprise.soap.sforce.com';
        private String UserTerritoryDeleteHeader_hns = 'UserTerritoryDeleteHeader=urn:enterprise.soap.sforce.com';
        private String LoginScopeHeader_hns = 'LoginScopeHeader=urn:enterprise.soap.sforce.com';
        private String AllowFieldTruncationHeader_hns = 'AllowFieldTruncationHeader=urn:enterprise.soap.sforce.com';
        private String DebuggingHeader_hns = 'DebuggingHeader=urn:enterprise.soap.sforce.com';
        private String AllOrNoneHeader_hns = 'AllOrNoneHeader=urn:enterprise.soap.sforce.com';
        private String LocaleOptions_hns = 'LocaleOptions=urn:enterprise.soap.sforce.com';
        private String OwnerChangeOptions_hns = 'OwnerChangeOptions=urn:enterprise.soap.sforce.com';
        private String AssignmentRuleHeader_hns = 'AssignmentRuleHeader=urn:enterprise.soap.sforce.com';
        private String DisableFeedTrackingHeader_hns = 'DisableFeedTrackingHeader=urn:enterprise.soap.sforce.com';
        private String StreamingEnabledHeader_hns = 'StreamingEnabledHeader=urn:enterprise.soap.sforce.com';
        private String[] ns_map_type_info = new String[]{'urn:fault.enterprise.soap.sforce.com', 'faultEnterpriseSoapSforceCom', 'urn:enterprise.soap.sforce.com', 'enterpriseSoapSforceCom', 'urn:sobject.enterprise.soap.sforce.com', 'sobjectEnterpriseSoapSforceCom'};
        public enterpriseSoapSforceCom.SearchResult search_x(String searchString) {
            enterpriseSoapSforceCom.search_element request_x = new enterpriseSoapSforceCom.search_element();
            enterpriseSoapSforceCom.searchResponse_element response_x;
            request_x.searchString = searchString;
            Map<String, enterpriseSoapSforceCom.searchResponse_element> response_map_x = new Map<String, enterpriseSoapSforceCom.searchResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'urn:enterprise.soap.sforce.com',
              'search',
              'urn:enterprise.soap.sforce.com',
              'searchResponse',
              'enterpriseSoapSforceCom.searchResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.result;
        
            public enterpriseSoapSforceCom.LoginResult login(String username,String password) {
            enterpriseSoapSforceCom.login_element request_x = new enterpriseSoapSforceCom.login_element();
            enterpriseSoapSforceCom.loginResponse_element response_x;
            request_x.username = username;
            request_x.password = password;
            Map<String, enterpriseSoapSforceCom.loginResponse_element> response_map_x = new Map<String, enterpriseSoapSforceCom.loginResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'urn:enterprise.soap.sforce.com',
              'login',
              'urn:enterprise.soap.sforce.com',
              'loginResponse',
              'enterpriseSoapSforceCom.loginResponse_element'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.result;
        }
            
            
        }
        
        
        }

 

 

enterpriseSoapSforceCom.LoginResult lr=new enterpriseSoapSforceCom.LoginResult();
enterpriseSoapSforceCom.soap s=new enterpriseSoapSforceCom.soap();
lr=s.login(james@yahoo.com','xxxxxxxx);
//String g=lr.sessionid;
//System.debug('The value of the session id in the new variable s is'+g);
s.endpoint_x=lr.serverurl;
enterpriseSoapSforceCom.SessionHeader_element SessionHeader=new enterpriseSoapSforceCom.SessionHeader_element();
sessionheader.sessionid=lr.sessionid;
//lr.serverurl;
//system.debug('The value of the url in the new variable s is'+url);
//s.inputHttpHeaders_x = new Map<String, String>();
//Setting a basic authentication header
//s.inputHttpHeaders_x.put('Authorization', 'g');
//s.inputHttpHeaders_x .put('New Url','https://na15.salesforce.com/services/Soap/c/28.0/00Di0000000J1Tf/0DFi0000000PCEo');
enterpriseSoapSforceCom.QueryResult qResult=new enterpriseSoapSforceCom.QueryResult();
qResult = null;
//System.debug('The value of the session id in the new variable s is'+s);
String soqlQuery='SELECT name FROM Contact';
qResult = s.query(soqlQuery);
System.debug('The value of the opportunity object opp is'+qResult);