118.14. 使用 Salesforce Composite API 提交批处理中的多个请求
Composite API batch 操作(composite-batch)允许您在批处理中累积多个请求,然后一次性提交请求,从而节省多个单独请求的往返成本。然后,每个响应都会在带有保留顺序的响应列表中接收,以便第 n 个请求响应位于响应的第 n 个位置。
注意
结果可能与 API 到 API,因此请求的结果以 java.lang.Object 形式提供。在大多数情况下,结果将是 java.util.Map,带有字符串键和值或其他 java.util.Map 作为值。请求以 JSON 格式进行,并包含某种类型信息(例如,它知道什么是字符串,以及哪些值是数字)。
让我们来看一个示例:
final String acountId = ...
final SObjectBatch batch = new SObjectBatch("38.0");
final Account updates = new Account();
updates.setName("NewName");
batch.addUpdate("Account", accountId, updates);
final Account newAccount = new Account();
newAccount.setName("Account created from Composite batch API");
batch.addCreate(newAccount);
batch.addGet("Account", accountId, "Name", "BillingPostalCode");
batch.addDelete("Account", accountId);
final SObjectBatchResponse response = template.requestBody("salesforce:composite-batch", batch, SObjectBatchResponse.class);
boolean hasErrors = response.hasErrors(); // if any of the requests has resulted in either 4xx or 5xx HTTP status
final List<SObjectBatchResult> results = response.getResults(); // results of three operations sent in batch
final SObjectBatchResult updateResult = results.get(0); // update result
final int updateStatus = updateResult.getStatusCode(); // probably 204
final Object updateResultData = updateResult.getResult(); // probably null
final SObjectBatchResult createResult = results.get(1); // create result
@SuppressWarnings("unchecked")
final Map<String, Object> createData = (Map<String, Object>) createResult.getResult();
final String newAccountId = createData.get("id"); // id of the new account, this is for JSON, for XML it would be createData.get("Result").get("id")
final SObjectBatchResult retrieveResult = results.get(2); // retrieve result
@SuppressWarnings("unchecked")
final Map<String, Object> retrieveData = (Map<String, Object>) retrieveResult.getResult();
final String accountName = retrieveData.get("Name"); // Name of the retrieved account, this is for JSON, for XML it would be createData.get("Account").get("Name")
final String accountBillingPostalCode = retrieveData.get("BillingPostalCode"); // Name of the retrieved account, this is for JSON, for XML it would be createData.get("Account").get("BillingPostalCode")
final SObjectBatchResult deleteResult = results.get(3); // delete result
final int updateStatus = deleteResult.getStatusCode(); // probably 204
final Object updateResultData = deleteResult.getResult(); // probably null