sap-cloud-sdk

How to read OData Batch Response with the generic OData client?


I am trying to perform a batch read request with the generic OData client. The result works, however I have the feeling that it can be done better. But I have this one understanding questions.

I took the example from the doc and converted it a bit, since I want to have multiple reads in one batch..obviously. So my first request looks like this:

String servicePath = "/sap/opu/odata4/sap/zservice/srvd/sap/zservice/0001/";
String entityName = "Product";
HttpClient httpClient = HttpClientAccessor.getHttpClient(httpDestination);

ODataRequestBatch requestBatch = new ODataRequestBatch(servicePath, ODataProtocol.V4);

products.forEach(p -> {
  StructuredQuery query = StructuredQuery.onEntity("Product", ODataProtocol.V4);
  query.select("ProductCategory", "Product", "Price");

  query.filter(FieldReference.of("ProductCategory").equalTo(category),
  FieldReference.of("Product").equalTo(p));
  String encodedQuery = query.getEncodedQueryString();

  ODataRequestRead request = new ODataRequestRead(servicePath, entityName, encodedQuery,
  ODataProtocol.V4);
  requestBatch.addRead(request);
});

ODataRequestResultMultipartGeneric batchResult = requestBatch.execute(httpClient);

Now comes the part where I am unsure how to read the result. According to the documentation the following is done, which if fine, as long as I have just one read.

// extract information from batch response, by referring to the individual OData request reference
ODataRequestResultGeneric queryResult = batchResult.getResult(request);
List<Map<String, Object>> listOfEntityFields = queryResult.asListOfMaps();

In my example though, I have a loop and the variable request is unreachable/always different.

I now go the way that I have the result using the method batchResult.getBatchedResponses() the httpReposonses output, read me here the answers, make a JSONObject from it and then work with the results. But somehow I can't get rid of the feeling that I'm missing something here. Can you possibly help me on the hint?


Solution

  • You can use a list to store the request elements and then iterate over the request elements to get the results.

    List<ODataRequestRead> readRequests = new ArrayList<>();
    products.forEach(p -> {
      ...
    
      ODataRequestRead request = new ODataRequestRead(servicePath, entityName, encodedQuery,ODataProtocol.V4);
      readRequests.add(request);
      requestBatch.addRead(request);
      ...
    });
    
    readRequests.forEach(request -> {
                final ODataRequestResultGeneric result = batchResult.getResult(request);
    });